使用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()
}
讨论数量: 2

服务器重启或宕机就歇菜了

1个月前 评论

token 不行?这个搞?

1个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!