소스 검색

解决mqtt一直断开重连问题,clientid冲突

sl 3 주 전
부모
커밋
5bcd903413

+ 13 - 6
jeecg-module-interlock/src/main/java/org/jeecg/modules/mqtt/component/MqttPushClient.java

@@ -9,6 +9,7 @@ import org.springframework.stereotype.Component;
 
 import java.util.HashMap;
 import java.util.Map;
+import java.util.UUID;
 
 /**
  * ClassName: MqttPushClient
@@ -46,7 +47,9 @@ public class MqttPushClient {
     public void connect(String host, String clientID, String username, String password, int timeout, int keepalive) {
         MqttClient client;
         try {
-            client = new MqttClient(host, clientID, new MemoryPersistence());
+            String clientID1 = clientID + "_msg" + UUID.randomUUID();
+            System.out.println("当前客户的mqttId是:" +  clientID1);
+            client = new MqttClient(host, clientID1, new MemoryPersistence());
             MqttConnectOptions options = new MqttConnectOptions();
             options.setAutomaticReconnect(true);
             options.setCleanSession(true);
@@ -61,11 +64,15 @@ public class MqttPushClient {
                     public void connectionLost(Throwable throwable) {
                         // 连接丢失后,一般在这里面进行重连
                         logger.info("连接断开,可以做重连");
-//                        try {
-//                            client.connect(options);
-//                        } catch (MqttException e) {
-//                            throw new RuntimeException(e);
-//                        }
+                        try {
+                            String clientID2 = clientID + "_msg" + UUID.randomUUID();
+                            System.out.println("当前客户的mqttId是:" +  clientID2);
+                            MqttClient client2 = new MqttClient(host, clientID, new MemoryPersistence());
+                            MqttPushClient.setClient(client2);
+                            client2.connect(options);
+                        } catch (MqttException e) {
+                            throw new RuntimeException(e);
+                        }
                     }
 
                     @Override

+ 1 - 1
jeecg-module-interlock/src/main/java/org/jeecg/modules/mqtt/controller/MqttTestController.java

@@ -80,7 +80,7 @@ public class MqttTestController {
         int num = 0;
         while(true){
             num+=1;
-            if(num>1000){
+            if(num>10){
                 System.out.println("发送了一千条消息,发送完毕");
                 return Result.OK("发送成功");
             }

+ 1 - 1
jeecg-module-system/jeecg-system-start/src/main/resources/application-dev.yml

@@ -45,7 +45,7 @@ spring:
     password: 302201
     #    测试服务器mqtt
     host-url: tcp://119.3.168.55:1883
-    clientId: mqttId
+    clientId: mqttId555
     completionTimeout: 3000
     timeout: 1000
     keepalive: 20