github.com/zly-app/zapp@v1.3.3/component/msgbus/topic.go (about) 1 /* 2 ------------------------------------------------- 3 Author : zlyuancn 4 date: 2021/3/19 5 Description : 6 ------------------------------------------------- 7 */ 8 9 package msgbus 10 11 import ( 12 "sync" 13 14 "github.com/zly-app/zapp/core" 15 ) 16 17 // 主题 18 type msgTopic struct { 19 subs map[uint32]*subscriber 20 mx sync.RWMutex // 用于锁 subs 21 } 22 23 func newMsgTopic() *msgTopic { 24 return &msgTopic{ 25 subs: make(map[uint32]*subscriber), 26 } 27 } 28 29 // 发布消息 30 func (t *msgTopic) Publish(topic string, msg interface{}) { 31 t.mx.RLock() 32 for _, sub := range t.subs { 33 sub.queue <- &channelMsg{ 34 topic: topic, 35 msg: msg, 36 } 37 } 38 t.mx.RUnlock() 39 } 40 41 // 订阅 42 func (t *msgTopic) Subscribe(threadCount int, handler core.MsgbusHandler) (subscriberId uint32) { 43 sub := newSubscriber(threadCount, handler) 44 subscriberId = nextSubscriberId() 45 46 t.mx.Lock() 47 t.subs[subscriberId] = sub 48 t.mx.Unlock() 49 50 return subscriberId 51 } 52 53 // 取消订阅, 会将订阅者关闭 54 func (t *msgTopic) Unsubscribe(subscribeId uint32) { 55 t.mx.Lock() 56 sub, ok := t.subs[subscribeId] 57 if ok { 58 sub.Close() 59 delete(t.subs, subscribeId) 60 } 61 t.mx.Unlock() 62 } 63 64 // 关闭主题 65 func (t *msgTopic) Close() { 66 t.mx.Lock() 67 for _, sub := range t.subs { 68 sub.Close() 69 } 70 71 // 如果不清除, 在调用 Publish 会导致panic 72 t.subs = make(map[uint32]*subscriber) 73 74 t.mx.Unlock() 75 }