github.com/zly-app/zapp@v1.3.3/component/msgbus/msgbus.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 msgbus struct {
    19  	global    *msgTopic // 用于接收全局消息
    20  	topics    map[string]*msgTopic
    21  	mx        sync.RWMutex // 用于锁 topics
    22  }
    23  
    24  func (m *msgbus) Publish(topic string, msg interface{}) {
    25  	m.global.Publish(topic, msg) // 发送消息到全局
    26  
    27  	m.mx.RLock()
    28  	t, ok := m.topics[topic]
    29  	m.mx.RUnlock()
    30  
    31  	if ok {
    32  		t.Publish(topic, msg)
    33  	}
    34  }
    35  
    36  func (m *msgbus) Subscribe(topic string, threadCount int, handler core.MsgbusHandler) (subscribeId uint32) {
    37  	m.mx.RLock()
    38  	t, ok := m.topics[topic]
    39  	m.mx.RUnlock()
    40  
    41  	if !ok {
    42  		m.mx.Lock()
    43  		t, ok = m.topics[topic]
    44  		if !ok {
    45  			t = newMsgTopic()
    46  			m.topics[topic] = t
    47  		}
    48  		m.mx.Unlock()
    49  	}
    50  	return t.Subscribe(threadCount, handler)
    51  }
    52  func (m *msgbus) SubscribeGlobal(threadCount int, handler core.MsgbusHandler) (subscribeId uint32) {
    53  	return m.global.Subscribe(threadCount, handler)
    54  }
    55  
    56  func (m *msgbus) Unsubscribe(topic string, subscribeId uint32) {
    57  	m.mx.RLock()
    58  	t, ok := m.topics[topic]
    59  	m.mx.RUnlock()
    60  
    61  	if ok {
    62  		t.Unsubscribe(subscribeId)
    63  	}
    64  }
    65  func (m *msgbus) UnsubscribeGlobal(subscribeId uint32) {
    66  	m.global.Unsubscribe(subscribeId)
    67  }
    68  
    69  func (m *msgbus) CloseTopic(topic string) {
    70  	m.mx.Lock()
    71  	t, ok := m.topics[topic]
    72  	if ok {
    73  		delete(m.topics, topic)
    74  	}
    75  	m.mx.Unlock()
    76  
    77  	if ok {
    78  		t.Close()
    79  	}
    80  }
    81  func (m *msgbus) Close() {
    82  	m.mx.Lock()
    83  	m.global.Close()
    84  	m.global = newMsgTopic()
    85  	for _, t := range m.topics {
    86  		t.Close()
    87  	}
    88  	m.topics = make(map[string]*msgTopic)
    89  	m.mx.Unlock()
    90  }
    91  
    92  func NewMsgbus() core.IMsgbus {
    93  	return &msgbus{
    94  		global: newMsgTopic(),
    95  		topics: make(map[string]*msgTopic),
    96  	}
    97  }