From b93b67a7e237cbf59569dcaacfa84257856ba16e Mon Sep 17 00:00:00 2001 From: liuxiaolong <liuxiaolong@aiotlink.com> Date: 星期三, 30 十二月 2020 14:19:34 +0800 Subject: [PATCH] 添加DeSub,优化订阅主题消息通道 --- micronode.go | 51 ++++++++++++++++++++++++++++++++++++++++++--------- 1 files changed, 42 insertions(+), 9 deletions(-) diff --git a/micronode.go b/micronode.go index 46731d7..1cc69d7 100644 --- a/micronode.go +++ b/micronode.go @@ -19,7 +19,7 @@ serverId string fnLog func(...interface{}) - SubChM map[string]chan *MsgInfo //浠ヨ闃呯殑涓婚涓簁ey + SubCh chan *MsgInfo } func NewMicroNode(ctx context.Context,q chan os.Signal, serverId string, reg *RegisterInfo, procInfo *ProcInfo,fnLog func(v ...interface{})) (*MicroNode, error){ @@ -33,11 +33,8 @@ handle: handle, reg: reg, procInfo: procInfo, - fnLog: fnLog, - SubChM: make(map[string]chan *MsgInfo), - } - for _,subTopic := range reg.SubTopic { - mn.SubChM[subTopic] = make(chan *MsgInfo, 512) + fnLog: fnLog, + SubCh: make(chan *MsgInfo, 512), } return mn, nil @@ -102,9 +99,7 @@ if msgS != nil { //鏀跺埌鍏跺畠杩涚▼鐨勫彂甯冩秷鎭� ms.printLog("Recv Sub Message:", string(msgS.Body)) - if ch,ok := ms.SubChM[msgS.Topic];ok { - ch <- msgS - } + ms.SubCh <- msgS } if msgR != nil { //鏀跺埌鍏跺畠杩涚▼鐨勮姹傛秷鎭� @@ -259,8 +254,46 @@ return ms.handle.Pub(nodes, pi) } +//璁㈤槄涓婚 func (ms *MicroNode) Subscribe(topics []string) { ms.handle.Sub(topics) + for _,t := range topics { + if ms.reg.SubTopic == nil { + ms.reg.SubTopic = make([]string, 0) + } + found := false + for _,it := range ms.reg.SubTopic { + if it == t { + found = true + break + } + } + if !found { + ms.reg.SubTopic = append(ms.reg.SubTopic, t) + } + } +} + +//鍙栨秷璁㈤槄鐨勪富棰� +func (ms *MicroNode) DeSub(topics []string) { + ms.printLog("DeSub topics:", topics) + ms.handle.DeSub(topics) + if ms.reg.SubTopic != nil { + var leftTopics []string + for _,t := range ms.reg.SubTopic { + found := false + for _,it := range topics { + if it == t { + found = true + break + } + } + if !found { + leftTopics = append(leftTopics, t) + } + } + ms.reg.SubTopic = leftTopics + } } //free handle -- Gitblit v1.8.0