1. 程式人生 > >對 eclipse 封裝的 golang mqtt client 進行二次封裝, 將通訊層做成同步介面

對 eclipse 封裝的 golang mqtt client 進行二次封裝, 將通訊層做成同步介面

用途:

封裝用於微服務之間的通訊

介面:

type CMqttComm interface {
	Connect(isReConnect bool)
	SetMessageBus(host string, port int, username string, userpwd string)
	Subscribe(action string, topic string, qos int, handler CHandler, user interface{}) error
	UnSubscribe(action string, topic string) error
	Send(action string, topic string, request string, qos int, timeout int) (response string, err error)
	Get(topic string, request string, qos int, timeout int) (response string, err error)
	Post(topic string, request string, qos int, timeout int) (response string, err error)
	Put(topic string, request string, qos int, timeout int) (response string, err error)
	Delete(topic string, request string, qos int, timeout int) (response string, err error)
	Updated(topic string, request string, qos int) error
	Deleted(topic string, request string, qos int) error
}

模擬的是 Restful 的風格

各個微服務之間僅僅需要關注自己所關注的請求, 再 CHandler 中處理

type CHandler interface {
	Handle(topic string, request string, mc CMqttComm, user interface{}) (response string, err error)
}

所有請求 struct 都實現這個介面, 然後呼叫 Subscribe, 就可以接收到其他微服務傳送過來的訊息

每一個 handler 都是一個 goroutine

Send, Get, Post, 等介面都是同步介面, 可以直接拿到回覆結果

原始碼位置: