Explorar el Código

优化mqttclient.go通用封装

niujiuru hace 1 mes
padre
commit
5720503762
Se han modificado 1 ficheros con 9 adiciones y 1 borrados
  1. 9 1
      mqtt_reporter/client.go

+ 9 - 1
mqtt_reporter/client.go

@@ -124,17 +124,20 @@ func (c *Client) run() {
 	}()
 	}()
 
 
 	for {
 	for {
+		// 1, 是否退出
 		if c.ctx.Err() != nil {
 		if c.ctx.Err() != nil {
 			return
 			return
 		}
 		}
 
 
-		if c.client.IsConnected() { // 已连接
+		// 2, 已连接时
+		if c.client.IsConnected() {
 			if !c.waitInterval(fastInterval) {
 			if !c.waitInterval(fastInterval) {
 				return
 				return
 			}
 			}
 			continue
 			continue
 		}
 		}
 
 
+		// 3, 尝试连接
 		if err := c.connect(); err != nil {
 		if err := c.connect(); err != nil {
 			if c.ctx.Err() != nil {
 			if c.ctx.Err() != nil {
 				return
 				return
@@ -146,6 +149,7 @@ func (c *Client) run() {
 			continue
 			continue
 		}
 		}
 
 
+		// 4, 重新订阅
 		if err := c.resubscribe(); err != nil {
 		if err := c.resubscribe(); err != nil {
 			if c.ctx.Err() != nil {
 			if c.ctx.Err() != nil {
 				return
 				return
@@ -246,6 +250,10 @@ func (c *Client) Publish(topic string, qos byte, retained bool, payload any) err
 	return c.waitToken(token)
 	return c.waitToken(token)
 }
 }
 
 
+/*
+消息回调需支持并发调用,并尽快返回,尽量避免耗时或阻塞操作, 此类类任务应交由独立的goroutine或通
+过消息队列来处理,避免阻塞mqtt底层的消息处理。
+*/
 func (c *Client) Subscribe(topic string, qos byte, handler mqtt.MessageHandler) error {
 func (c *Client) Subscribe(topic string, qos byte, handler mqtt.MessageHandler) error {
 	if topic == "" {
 	if topic == "" {
 		return ErrTopicEmpty
 		return ErrTopicEmpty