使用sync.Map和sync.Cond封装消息队列,有哪些弊端和优点
网络编程中,服务端接收客户端消息,读取出userID,把userID和msgBody关联起来,使用sync.Map和sync.Cond设计一个消息队列,这样的方式有啥弊端和优势,讨论讨论
type MessageQueue struct {
msgMap sync.Map
cond *sync.Cond
}
func NewMessageQueue() (msgQueue *MessageQueue) {
msgQueue = &MessageQueue{
msgMap: sync.Map{},
cond: sync.NewCond(new(sync.Mutex)),
}
return
}
func (q *MessageQueue) Push(k any, v any) {
q.msgMap.Store(k, v)
q.cond.Broadcast()
}
func (q *MessageQueue) Pop(fn func(k, v any)) {
q.Lock()
defer q.UnLock()
q.Wait()
q.msgMap.Range(func(k, v any) bool {
fn(k, v)
q.msgMap.Delete(k)
return true
})
}
func (q *MessageQueue) Load(k any, fn func(value any)) bool {
if v, ok := q.msgMap.Load(k); ok {
fn(v)
return ok
}
return true
}
func (q *MessageQueue) Lock() {
q.cond.L.Lock()
}
func (q *MessageQueue) UnLock() {
q.cond.L.Unlock()
}
func (q *MessageQueue) Wait() {
q.cond.Wait()
}
服务器重启或宕机就歇菜了
token 不行?这个搞?