我很难理解参考资料的运作方式。我想写一个非常简单的内存中的发布 - 订阅机制。这是代码:
package sockets
import (
"fmt"
"github.com/gorilla/websocket"
)
type hubSingleton struct {
Clients map[string][]*websocket.Conn
}
var instance *hubSingleton
func Hub() *hubSingleton {
if instance == nil {
fmt.Println("New instance created")
instance = &hubSingleton{}
}
instance.Clients = make(map[string][]*websocket.Conn, 6)
return instance
}
func (hub *hubSingleton) Subscribe(channel string, socket *websocket.Conn) error {
if _, ok := hub.Clients[channel]; !ok {
hub.Clients[channel] = make([]*websocket.Conn, 0)
}
hub.Clients[channel] = append(hub.Clients[channel], socket)
fmt.Println("Subscribe: ", hub.Clients)
return nil
}
func (hub *hubSingleton) Publish(channel string, message interface{}) {
fmt.Println("Publish: ", hub.Clients)
if _, ok := hub.Clients[channel]; !ok {
return
}
for i := 0; i < len(hub.Clients[channel]); i++ {
conn := hub.Clients[channel][i]
conn.WriteJSON(Message{status: "ok", content: message})
}
}
问题在于,每次我调用Hub()。Publish()或Hub()时,订阅()都会创建一个新的hubSingleton.Client。好吧,我不确定会发生什么,但这是运行程序的输出:
Publish: map[]
Subscribe: map[chan:[0xc820170000]]
Publish: map[]
Subscribe: map[chan:[0xc82008ac80]]
Publish: map[]
Publish: map[]
Publish: map[]
Subscribe: map[chan:[0xc820170140]]
Publish: map[]
每次调用Hub()时,添加到地图的订阅者都会消失。 我该怎么办,在调用之间保留地图中的更改?
答案 0 :(得分:2)
Hub
函数会在每次调用时创建一个新的客户端映射。将功能更改为:
func Hub() *hubSingleton {
if instance == nil {
fmt.Println("New instance created")
instance = &hubSingleton{}
instance.Clients = make(map[string][]*websocket.Conn, 6)
}
return instance
}
如果对Hub
的第一次调用来自请求处理程序,那么instance
上就会出现数据竞争。使用锁来修复比赛:
var (
instance *hubSingleton
mu sync.Mutex
)
func Hub() *hubSingleton {
mu.Lock()
defer mu.Unlock()
if instance == nil {
fmt.Println("New instance created")
instance = &hubSingleton{}
instance.Clients = make(map[string][]*websocket.Conn, 6)
}
return instance
}
更简单的方法是在使用前初始化实例:
var instance *hubSingleton
func newHub() *hubSingleton {
return &hubSingleton{Clients: make(map[string][]*websocket.Conn, 6)}
}
func main() {
instance = newHub()
...
}
如果处理程序同时调用Publish
和Subscribe
,则Clients
和Publish
中的Subscribe
上会有数据争用。