diff --git a/xymanager_service/src/main/java/com/shxy/xymanager_service/mqtt/MqttSubscriberService.java b/xymanager_service/src/main/java/com/shxy/xymanager_service/mqtt/MqttSubscriberService.java index 8a925f8..35165d6 100644 --- a/xymanager_service/src/main/java/com/shxy/xymanager_service/mqtt/MqttSubscriberService.java +++ b/xymanager_service/src/main/java/com/shxy/xymanager_service/mqtt/MqttSubscriberService.java @@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Iterator; @@ -32,6 +33,7 @@ public class MqttSubscriberService { RespMessageListener respMessageListener; @Resource NewCacheService newCacheService; + List topicList = new ArrayList<>(); @PostConstruct public void init() throws Exception { @@ -52,8 +54,24 @@ public class MqttSubscriberService { } // 订阅主题 for (String model : modelList) { - mqttClient.subscribe(TopicPrefix + model + RespSuffix, respMessageListener); - mqttClient.subscribe(TopicPrefix + model + DataSuffix, dataMessageListener); + String topic = TopicPrefix + model + RespSuffix; + mqttClient.subscribe(topic, respMessageListener); + topicList.add(topic); + topic = TopicPrefix + model + DataSuffix; + mqttClient.subscribe(topic, dataMessageListener); + topicList.add(topic); + } + } + + @PreDestroy + private void preDestroy() { + try { + mqttClient.unsubscribe(topicList.toArray(new String[0])); + if (mqttClient.isConnected()) { + mqttClient.disconnect(); + } + mqttClient.close(); + } catch (Exception ignore) { } } }