From 4b398ada89cd72d2b559167610d96aadce81c76c Mon Sep 17 00:00:00 2001 From: huangfeng Date: Mon, 9 Jun 2025 10:16:00 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E5=85=B3=E6=9C=BA=E5=89=8D=E5=8F=96?= =?UTF-8?q?=E6=B6=88=E5=B7=B2=E8=AE=A2=E9=98=85=E7=9A=84mqtt=E4=B8=BB?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mqtt/MqttSubscriberService.java | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) 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) { } } }