加锁
This commit is contained in:
parent
b20e67b951
commit
7e33fcf7c7
9
main.go
9
main.go
@ -6,6 +6,7 @@ import (
|
|||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/dgraph-io/badger"
|
"github.com/dgraph-io/badger"
|
||||||
@ -23,6 +24,7 @@ var (
|
|||||||
db *badger.DB
|
db *badger.DB
|
||||||
rssUrls Config
|
rssUrls Config
|
||||||
upgrader = websocket.Upgrader{}
|
upgrader = websocket.Upgrader{}
|
||||||
|
connMu sync.Mutex // 定义互斥锁
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
@ -75,10 +77,13 @@ func wsHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
if rssUrls.AutoUpdatePush > 0 {
|
if rssUrls.AutoUpdatePush > 0 {
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
|
connMu.Lock() // 加锁
|
||||||
if err := conn.WriteMessage(websocket.TextMessage, []byte("heartbeat")); err != nil {
|
if err := conn.WriteMessage(websocket.TextMessage, []byte("heartbeat")); err != nil {
|
||||||
log.Printf("heartbeat Write error: %v", err)
|
log.Printf("heartbeat Write error: %v", err)
|
||||||
|
connMu.Unlock() // 解锁
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
connMu.Unlock() // 解锁
|
||||||
time.Sleep(time.Duration(10) * time.Second)
|
time.Sleep(time.Duration(10) * time.Second)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
@ -90,13 +95,15 @@ func wsHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
log.Printf("Error getting feed from Redis: %v", err)
|
log.Printf("Error getting feed from Redis: %v", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
connMu.Lock() // 加锁
|
||||||
err = conn.WriteMessage(websocket.TextMessage, []byte(feedJSON))
|
err = conn.WriteMessage(websocket.TextMessage, []byte(feedJSON))
|
||||||
//错误直接关闭更新
|
//错误直接关闭更新
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Error sending message or Connection closed: %v", err)
|
log.Printf("Error sending message or Connection closed: %v", err)
|
||||||
|
connMu.Unlock() // 解锁
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
connMu.Unlock() // 解锁
|
||||||
}
|
}
|
||||||
//如果未配置则不自动更新
|
//如果未配置则不自动更新
|
||||||
if rssUrls.AutoUpdatePush == 0 {
|
if rssUrls.AutoUpdatePush == 0 {
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user