Explorar el Código

完善 MQTT 客户端封装,支持断线重连与订阅自动恢复,通过独立锁避免订阅恢复竞态。

niujiuru hace 1 mes
padre
commit
90ff33d7d2
Se han modificado 3 ficheros con 34 adiciones y 3 borrados
  1. 10 0
      mqtt_reporter/client.go
  2. 11 3
      mqtt_reporter/config.go
  3. 13 0
      mqtt_reporter/reporter.go

+ 10 - 0
mqtt_reporter/client.go

@@ -47,10 +47,12 @@ type subscription struct {
 
 type Client struct {
 	client  mqtt.Client
+	config  ClientConfig
 	ctx     context.Context
 	cancel  context.CancelFunc
 	done    chan struct{}
 	mu      sync.Mutex
+	subMu   sync.Mutex
 	subs    map[string]subscription ////// 订阅主题与处理回调
 	started bool
 	closed  bool
@@ -90,6 +92,7 @@ func NewClient(config ClientConfig, ctx context.Context) (*Client, error) {
 
 	return &Client{
 		client: mqtt.NewClient(opts),
+		config: config,
 		ctx:    ctx,
 		cancel: cancel,
 		done:   make(chan struct{}),
@@ -138,6 +141,7 @@ func (c *Client) run() {
 		}
 
 		// 3, 尝试连接
+		baseapp.Logger.Infof("[%s] 尝试连接服务器(%s)...", MODULE_NAME, c.config.Broker)
 		if err := c.connect(); err != nil {
 			if c.ctx.Err() != nil {
 				return
@@ -190,6 +194,9 @@ func (c *Client) connect() error {
 }
 
 func (c *Client) resubscribe() error {
+	c.subMu.Lock()
+	defer c.subMu.Unlock()
+
 	c.mu.Lock()
 	subs := make(map[string]subscription, len(c.subs))
 	maps.Copy(subs, c.subs)
@@ -265,6 +272,9 @@ func (c *Client) Subscribe(topic string, qos byte, handler mqtt.MessageHandler)
 		return ErrNilHandler
 	}
 
+	c.subMu.Lock()
+	defer c.subMu.Unlock()
+
 	c.mu.Lock()
 	if err := c.checkStateLocked(); err != nil {
 		c.mu.Unlock()

+ 11 - 3
mqtt_reporter/config.go

@@ -19,9 +19,14 @@ type ServerConfig struct {
 }
 
 type MQTTServer struct {
-	Enable        bool   `json:"enable"`
-	Name          string `json:"name"`
-	Protocol      string `json:"protocol"`
+	Enable   bool   `json:"enable"`
+	Name     string `json:"name"`
+	Protocol string `json:"protocol"`
+
+	EnableOfflineStorage bool `json:"enableOfflineStorage"`
+	DataRetentionDays    int  `json:"dataRetentionDays"`
+	ImagRetentionDays    int  `json:"imagRetentionDays"`
+
 	BrokerAddress string `json:"brokerAddress"`
 	Username      string `json:"username"`
 	Password      string `json:"password"`
@@ -58,6 +63,9 @@ const defaultConfig = `{
       "enable": true,
       "name": "yfkj's mqtt server",
       "protocol": "yfkj-private",
+			"enableOfflineStorage": "true",
+			"dataRetentionDays": 0,
+			"imagRetentionDays": 0,
       "brokerAddress": "tcp://8.136.98.49:61883",
       "username": "user",
       "password": "f335bf402c655ee5fd2b5300905124e",

+ 13 - 0
mqtt_reporter/reporter.go

@@ -1,3 +1,16 @@
 package mqttreporter
 
+import "context"
+
 const MODULE_NAME = "Reporter"
+
+var (
+	Reporter *MQTTReporter
+)
+
+type MQTTReporter struct {
+	config  ServerConfig
+	clients map[string]*Client
+	ctx     context.Context
+	cancel  context.CancelFunc
+}