|
|
@@ -2,411 +2,58 @@ package com.iot.platform.mqtt;
|
|
2
|
2
|
|
|
3
|
3
|
import com.fasterxml.jackson.core.type.TypeReference;
|
|
4
|
4
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
5
|
+import com.iot.platform.config.IotProperties;
|
|
5
|
6
|
import com.iot.platform.domain.SysController;
|
|
6
|
7
|
import com.iot.platform.service.SysControllerService;
|
|
7
|
8
|
import com.iot.platform.service.TDengineService;
|
|
8
|
9
|
import org.eclipse.paho.client.mqttv3.*;
|
|
9
|
|
-import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
|
10
|
|
-import com.iot.platform.config.IotProperties;
|
|
11
|
10
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
12
|
11
|
import org.springframework.beans.factory.annotation.Qualifier;
|
|
13
|
12
|
import org.springframework.context.annotation.DependsOn;
|
|
14
|
13
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
|
15
|
14
|
import org.springframework.stereotype.Component;
|
|
16
|
15
|
|
|
17
|
|
-import javax.annotation.PostConstruct;
|
|
18
|
|
-import javax.annotation.PreDestroy;
|
|
19
|
|
-import java.net.InetSocketAddress;
|
|
20
|
|
-import java.net.Socket;
|
|
21
|
|
-import java.nio.charset.StandardCharsets;
|
|
22
|
16
|
import java.time.LocalDate;
|
|
23
|
17
|
import java.time.LocalDateTime;
|
|
24
|
18
|
import java.time.format.DateTimeFormatter;
|
|
25
|
19
|
import java.util.*;
|
|
26
|
|
-import java.util.concurrent.*;
|
|
27
|
|
-import java.util.concurrent.atomic.AtomicBoolean;
|
|
28
|
|
-import org.slf4j.Logger;
|
|
29
|
|
-import org.slf4j.LoggerFactory;
|
|
|
20
|
+import java.util.concurrent.ExecutorService;
|
|
|
21
|
+import java.util.concurrent.ScheduledExecutorService;
|
|
|
22
|
+import java.util.concurrent.TimeUnit;
|
|
30
|
23
|
|
|
31
|
|
-@Component
|
|
32
|
24
|
@SuppressWarnings("unchecked")
|
|
33
|
|
-public class MqttDynamicConsumer {
|
|
34
|
|
-
|
|
35
|
|
- private static final Logger log = LoggerFactory.getLogger(MqttDynamicConsumer.class);
|
|
36
|
|
-
|
|
37
|
|
- @Autowired
|
|
38
|
|
- private SysControllerService sysControllerService;
|
|
39
|
|
-
|
|
40
|
|
- @Autowired
|
|
41
|
|
- private TDengineService tdengineService;
|
|
|
25
|
+@Component
|
|
|
26
|
+@DependsOn({"sysControllerService", "tdengineService"})
|
|
|
27
|
+public class MqttDynamicConsumer extends AbstractDynamicMqttConsumer {
|
|
42
|
28
|
|
|
|
29
|
+ private final SysControllerService sysControllerService;
|
|
|
30
|
+ private final TDengineService tdengineService;
|
|
|
31
|
+ private final StringRedisTemplate stringRedisTemplate;
|
|
43
|
32
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
|
44
|
|
- @Autowired
|
|
45
|
|
- private StringRedisTemplate stringRedisTemplate;
|
|
46
|
33
|
|
|
47
|
34
|
@Autowired
|
|
48
|
|
- private IotProperties iotProperties;
|
|
49
|
|
-
|
|
50
|
|
- // MQTT 配置
|
|
51
|
|
- private String brokerUrl;
|
|
52
|
|
- private String brokerHost;
|
|
53
|
|
- private int brokerPort;
|
|
54
|
|
- private static final int QOS = 1;
|
|
55
|
|
- private static final int CONNECT_TIMEOUT = 3000;
|
|
56
|
|
- private static final int RECONNECT_INTERVAL = 5000;
|
|
57
|
|
- private static final int MAX_BATCH_SIZE = 50;
|
|
58
|
|
-
|
|
59
|
|
- private String mqttUsername;
|
|
60
|
|
- private String mqttPassword;
|
|
61
|
|
-
|
|
62
|
|
- private MqttClient mqttClient;
|
|
63
|
|
- private MqttConnectOptions connOpts;
|
|
64
|
|
- private final Set<String> currentTopicSet = new CopyOnWriteArraySet<>();
|
|
65
|
|
- private final AtomicBoolean isConnected = new AtomicBoolean(false);
|
|
66
|
|
- private final Object lock = new Object();
|
|
67
|
|
-
|
|
68
|
|
- private final ScheduledExecutorService coreExecutor;
|
|
69
|
|
- private final ExecutorService writeExecutor;
|
|
70
|
|
-
|
|
71
|
|
- @Autowired
|
|
72
|
|
- public MqttDynamicConsumer(@Qualifier("mqttCoreExecutor") ScheduledExecutorService coreExecutor,
|
|
73
|
|
- @Qualifier("mqttWriteExecutor") ExecutorService writeExecutor) {
|
|
74
|
|
- this.coreExecutor = coreExecutor;
|
|
75
|
|
- this.writeExecutor = writeExecutor;
|
|
76
|
|
- }
|
|
77
|
|
-
|
|
78
|
|
- @PostConstruct
|
|
79
|
|
- @DependsOn({"sysControllerService", "tdengineService"})
|
|
80
|
|
- public void initMqttConnection() {
|
|
81
|
|
- this.brokerUrl = iotProperties.getMqtt().getBrokerUrl();
|
|
82
|
|
- String brokerAddr = this.brokerUrl.replace("tcp://", "");
|
|
83
|
|
- int colonIdx = brokerAddr.lastIndexOf(':');
|
|
84
|
|
- this.brokerHost = brokerAddr.substring(0, colonIdx);
|
|
85
|
|
- this.brokerPort = Integer.parseInt(brokerAddr.substring(colonIdx + 1));
|
|
86
|
|
- this.mqttUsername = iotProperties.getMqtt().getUsername();
|
|
87
|
|
- this.mqttPassword = iotProperties.getMqtt().getPassword();
|
|
88
|
|
-
|
|
89
|
|
- log.info(">>> 开始初始化 MQTT 服务...");
|
|
90
|
|
-
|
|
91
|
|
- CompletableFuture<Boolean> connectFuture = CompletableFuture.supplyAsync(() -> {
|
|
92
|
|
- int initRetry = 0;
|
|
93
|
|
- while (initRetry < 3 && !isConnected.get()) {
|
|
94
|
|
- try {
|
|
95
|
|
- if (refreshMqttSubscription()) {
|
|
96
|
|
- log.info(">>> MQTT 初始化成功");
|
|
97
|
|
- return true;
|
|
98
|
|
- }
|
|
99
|
|
- } catch (Exception e) {
|
|
100
|
|
- log.error("MQTT 启动初始化失败(第" + (initRetry + 1) + "次):", e);
|
|
101
|
|
- }
|
|
102
|
|
- initRetry++;
|
|
103
|
|
- try {
|
|
104
|
|
- Thread.sleep(RECONNECT_INTERVAL * initRetry);
|
|
105
|
|
- } catch (InterruptedException ex) {
|
|
106
|
|
- Thread.currentThread().interrupt();
|
|
107
|
|
- break;
|
|
108
|
|
- }
|
|
109
|
|
- }
|
|
110
|
|
- return false;
|
|
111
|
|
- }, coreExecutor);
|
|
112
|
|
-
|
|
113
|
|
- try {
|
|
114
|
|
- Boolean connected = connectFuture.get(10, TimeUnit.SECONDS);
|
|
115
|
|
- if (!connected) {
|
|
116
|
|
- log.error("!!! MQTT 启动失败(超时),触发后台重连机制");
|
|
117
|
|
- triggerReconnect();
|
|
118
|
|
- }
|
|
119
|
|
- } catch (TimeoutException e) {
|
|
120
|
|
- log.error("MQTT 初始化超时(10秒),触发后台重连机制");
|
|
121
|
|
- triggerReconnect();
|
|
122
|
|
- } catch (InterruptedException e) {
|
|
123
|
|
- Thread.currentThread().interrupt();
|
|
124
|
|
- log.error("MQTT 初始化被中断");
|
|
125
|
|
- triggerReconnect();
|
|
126
|
|
- } catch (ExecutionException e) {
|
|
127
|
|
- log.error("MQTT 初始化执行异常: ", e.getCause());
|
|
128
|
|
- triggerReconnect();
|
|
129
|
|
- }
|
|
|
35
|
+ public MqttDynamicConsumer(IotProperties iotProperties,
|
|
|
36
|
+ @Qualifier("mqttCoreExecutor") ScheduledExecutorService coreExecutor,
|
|
|
37
|
+ @Qualifier("mqttWriteExecutor") ExecutorService writeExecutor,
|
|
|
38
|
+ SysControllerService sysControllerService,
|
|
|
39
|
+ TDengineService tdengineService,
|
|
|
40
|
+ StringRedisTemplate stringRedisTemplate) {
|
|
|
41
|
+ super(iotProperties, coreExecutor, writeExecutor);
|
|
|
42
|
+ this.sysControllerService = sysControllerService;
|
|
|
43
|
+ this.tdengineService = tdengineService;
|
|
|
44
|
+ this.stringRedisTemplate = stringRedisTemplate;
|
|
130
|
45
|
}
|
|
131
|
46
|
|
|
132
|
|
- private void initMqttConnectOptions() {
|
|
133
|
|
- if (connOpts != null) return;
|
|
134
|
|
- try {
|
|
135
|
|
- connOpts = new MqttConnectOptions();
|
|
136
|
|
- connOpts.setCleanSession(false);
|
|
137
|
|
- connOpts.setAutomaticReconnect(true);
|
|
138
|
|
- connOpts.setConnectionTimeout(10);
|
|
139
|
|
- connOpts.setKeepAliveInterval(60);
|
|
140
|
|
- connOpts.setMaxInflight(10);
|
|
141
|
|
- connOpts.setMaxReconnectDelay(30);
|
|
142
|
|
- connOpts.setUserName(mqttUsername);
|
|
143
|
|
- connOpts.setPassword(mqttPassword.toCharArray());
|
|
144
|
|
- } catch (Exception e) {
|
|
145
|
|
- log.error("初始化 MQTT 配置失败:" + e.getMessage());
|
|
146
|
|
- throw new RuntimeException(e);
|
|
147
|
|
- }
|
|
|
47
|
+ @Override
|
|
|
48
|
+ protected List<String> fetchTopics() {
|
|
|
49
|
+ return sysControllerService.selectall();
|
|
148
|
50
|
}
|
|
149
|
51
|
|
|
150
|
|
- public boolean refreshMqttSubscription() {
|
|
151
|
|
- synchronized (lock) {
|
|
152
|
|
- try {
|
|
153
|
|
- initMqttConnectOptions();
|
|
154
|
|
- List<String> latestTopicList = sysControllerService.selectall();
|
|
155
|
|
- log.info("🔍 查询到 Topic 列表: " + latestTopicList);
|
|
156
|
|
-
|
|
157
|
|
- if (latestTopicList == null || latestTopicList.isEmpty()) {
|
|
158
|
|
- log.error("未查询到 Topic,取消所有订阅");
|
|
159
|
|
- unsubscribeAll();
|
|
160
|
|
- currentTopicSet.clear();
|
|
161
|
|
- return false;
|
|
162
|
|
- }
|
|
163
|
|
-
|
|
164
|
|
- Set<String> latestTopicSet = new HashSet<>();
|
|
165
|
|
- for (String topic : latestTopicList) {
|
|
166
|
|
- if (topic != null && !topic.trim().isEmpty()) {
|
|
167
|
|
- latestTopicSet.add(topic.trim());
|
|
168
|
|
- }
|
|
169
|
|
- }
|
|
170
|
|
-
|
|
171
|
|
- if (latestTopicSet.equals(currentTopicSet)) {
|
|
172
|
|
- log.info("Topic 列表无变化,无需刷新订阅关系");
|
|
173
|
|
- if (!isConnected.get() && !latestTopicSet.isEmpty()) {
|
|
174
|
|
- return connectAndSubscribe(latestTopicSet);
|
|
175
|
|
- }
|
|
176
|
|
- return true;
|
|
177
|
|
- }
|
|
178
|
|
-
|
|
179
|
|
- Set<String> topicsToAdd = new HashSet<>(latestTopicSet);
|
|
180
|
|
- topicsToAdd.removeAll(currentTopicSet);
|
|
181
|
|
- Set<String> topicsToRemove = new HashSet<>(currentTopicSet);
|
|
182
|
|
- topicsToRemove.removeAll(latestTopicSet);
|
|
183
|
|
-
|
|
184
|
|
- if (!isConnected.get()) {
|
|
185
|
|
- return connectAndSubscribe(latestTopicSet);
|
|
186
|
|
- } else {
|
|
187
|
|
- if (!topicsToRemove.isEmpty()) unsubscribeTopics(topicsToRemove);
|
|
188
|
|
- if (!topicsToAdd.isEmpty()) subscribeTopics(topicsToAdd);
|
|
189
|
|
- }
|
|
190
|
|
-
|
|
191
|
|
- currentTopicSet.clear();
|
|
192
|
|
- currentTopicSet.addAll(latestTopicSet);
|
|
193
|
|
- log.info("MQTT 订阅刷新完成,当前数量:" + currentTopicSet.size());
|
|
194
|
|
- return true;
|
|
195
|
|
-
|
|
196
|
|
- } catch (Exception e) {
|
|
197
|
|
- log.error("MQTT 订阅刷新失败:", e);
|
|
198
|
|
- return false;
|
|
199
|
|
- }
|
|
200
|
|
- }
|
|
201
|
|
- }
|
|
202
|
|
-
|
|
203
|
|
- private boolean connectAndSubscribe(Set<String> topicSet) {
|
|
204
|
|
- synchronized (lock) {
|
|
205
|
|
- if (isConnected.get() && mqttClient != null && mqttClient.isConnected()) {
|
|
206
|
|
- return true;
|
|
207
|
|
- }
|
|
208
|
|
- try {
|
|
209
|
|
- if (!checkServerAvailability()) {
|
|
210
|
|
- log.error("Broker 不可达,连接失败");
|
|
211
|
|
- return false;
|
|
212
|
|
- }
|
|
213
|
|
-
|
|
214
|
|
- if (mqttClient == null) {
|
|
215
|
|
- String clientId = generateUniqueClientId();
|
|
216
|
|
- MemoryPersistence persistence = new MemoryPersistence();
|
|
217
|
|
- mqttClient = new MqttClient(brokerUrl, clientId, persistence);
|
|
218
|
|
- setMqttCallback();
|
|
219
|
|
- }
|
|
220
|
|
-
|
|
221
|
|
- int connectRetry = 0;
|
|
222
|
|
- while (connectRetry < 3 && !mqttClient.isConnected()) {
|
|
223
|
|
- try {
|
|
224
|
|
- mqttClient.connect(connOpts);
|
|
225
|
|
- if (mqttClient.isConnected()) {
|
|
226
|
|
- isConnected.set(true);
|
|
227
|
|
- log.info("MQTT 连接成功,客户端 ID:" + mqttClient.getClientId());
|
|
228
|
|
- break;
|
|
229
|
|
- }
|
|
230
|
|
- } catch (MqttException e) {
|
|
231
|
|
- log.error("MQTT 连接失败(第" + (connectRetry + 1) + "次):" + e.getMessage());
|
|
232
|
|
- connectRetry++;
|
|
233
|
|
- if (connectRetry < 3) Thread.sleep(RECONNECT_INTERVAL * (connectRetry + 1));
|
|
234
|
|
- }
|
|
235
|
|
- }
|
|
236
|
|
-
|
|
237
|
|
- if (!mqttClient.isConnected()) {
|
|
238
|
|
- isConnected.set(false);
|
|
239
|
|
- return false;
|
|
240
|
|
- }
|
|
241
|
|
-
|
|
242
|
|
- if (!topicSet.isEmpty()) {
|
|
243
|
|
- List<String> topicList = new ArrayList<>(topicSet);
|
|
244
|
|
- for (int i = 0; i < topicList.size(); i += MAX_BATCH_SIZE) {
|
|
245
|
|
- int end = Math.min(i + MAX_BATCH_SIZE, topicList.size());
|
|
246
|
|
- List<String> batch = topicList.subList(i, end);
|
|
247
|
|
- batchSubscribeTopics(new HashSet<>(batch));
|
|
248
|
|
- Thread.sleep(100);
|
|
249
|
|
- }
|
|
250
|
|
- }
|
|
251
|
|
- return true;
|
|
252
|
|
-
|
|
253
|
|
- } catch (MqttException e) {
|
|
254
|
|
- log.error("MQTT 连接 + 订阅失败:", e);
|
|
255
|
|
- isConnected.set(false);
|
|
256
|
|
- triggerReconnect();
|
|
257
|
|
- return false;
|
|
258
|
|
- } catch (InterruptedException e) {
|
|
259
|
|
- Thread.currentThread().interrupt();
|
|
260
|
|
- log.error("MQTT 连接 + 订阅被中断");
|
|
261
|
|
- isConnected.set(false);
|
|
262
|
|
- return false;
|
|
263
|
|
- }
|
|
264
|
|
- }
|
|
265
|
|
- }
|
|
266
|
|
-
|
|
267
|
|
-
|
|
268
|
|
-
|
|
269
|
|
-
|
|
270
|
|
- private void batchSubscribeTopics(Set<String> topicSet) {
|
|
271
|
|
- if (topicSet.isEmpty() || !isConnected.get() || mqttClient == null) return;
|
|
272
|
|
- try {
|
|
273
|
|
- List<String> topicList = new ArrayList<>(topicSet);
|
|
274
|
|
- String[] topics = topicList.toArray(new String[0]);
|
|
275
|
|
- int[] qosArr = new int[topics.length];
|
|
276
|
|
- Arrays.fill(qosArr, QOS);
|
|
277
|
|
- mqttClient.subscribe(topics, qosArr);
|
|
278
|
|
- log.info("订阅完成:" + topicList.size() + "个 Topic");
|
|
279
|
|
- } catch (MqttException e) {
|
|
280
|
|
- log.error("批量订阅失败:" + e.getMessage());
|
|
281
|
|
- retrySubscribeBatch(new ArrayList<>(topicSet), 1);
|
|
282
|
|
- }
|
|
283
|
|
- }
|
|
284
|
|
-
|
|
285
|
|
- private void retrySubscribeBatch(List<String> batchTopics, int retryTimes) {
|
|
286
|
|
- for (int retry = 1; retry <= retryTimes; retry++) {
|
|
287
|
|
- try {
|
|
288
|
|
- Thread.sleep(1000 * retry);
|
|
289
|
|
- if (!isConnected.get() || mqttClient == null) continue;
|
|
290
|
|
- String[] topics = batchTopics.toArray(new String[0]);
|
|
291
|
|
- int[] qosArr = new int[topics.length];
|
|
292
|
|
- Arrays.fill(qosArr, QOS);
|
|
293
|
|
- mqttClient.subscribe(topics, qosArr);
|
|
294
|
|
- log.info("重试订阅成功(第" + retry + "次),数量:" + batchTopics.size());
|
|
295
|
|
- return;
|
|
296
|
|
- } catch (MqttException e) {
|
|
297
|
|
- log.error("重试订阅失败(第" + retry + "次):" + e.getMessage());
|
|
298
|
|
- } catch (InterruptedException e) {
|
|
299
|
|
- Thread.currentThread().interrupt();
|
|
300
|
|
- log.error("重试订阅被中断");
|
|
301
|
|
- break;
|
|
302
|
|
- }
|
|
303
|
|
- }
|
|
304
|
|
- log.error("批次订阅最终失败:" + batchTopics);
|
|
305
|
|
- }
|
|
306
|
|
-
|
|
307
|
|
- private void subscribeTopics(Set<String> topicsToAdd) {
|
|
308
|
|
- if (topicsToAdd.isEmpty() || !isConnected.get()) return;
|
|
309
|
|
- batchSubscribeTopics(topicsToAdd);
|
|
310
|
|
- }
|
|
311
|
|
-
|
|
312
|
|
- private void unsubscribeTopics(Set<String> topicsToRemove) {
|
|
313
|
|
- if (topicsToRemove.isEmpty() || !isConnected.get() || mqttClient == null) return;
|
|
314
|
|
- try {
|
|
315
|
|
- String[] topics = topicsToRemove.toArray(new String[0]);
|
|
316
|
|
- mqttClient.unsubscribe(topics);
|
|
317
|
|
- log.info("取消订阅完成,数量:" + topicsToRemove.size());
|
|
318
|
|
- } catch (MqttException e) {
|
|
319
|
|
- log.error("取消订阅失败:" + e.getMessage());
|
|
320
|
|
- }
|
|
321
|
|
- }
|
|
322
|
|
-
|
|
323
|
|
- private void unsubscribeAll() {
|
|
324
|
|
- if (currentTopicSet.isEmpty() || !isConnected.get() || mqttClient == null) return;
|
|
325
|
|
- try {
|
|
326
|
|
- String[] topics = currentTopicSet.toArray(new String[0]);
|
|
327
|
|
- mqttClient.unsubscribe(topics);
|
|
328
|
|
- log.info("取消所有订阅,数量:" + currentTopicSet.size());
|
|
329
|
|
- } catch (MqttException e) {
|
|
330
|
|
- log.error("取消所有订阅失败:" + e.getMessage());
|
|
331
|
|
- }
|
|
332
|
|
- }
|
|
333
|
|
-
|
|
334
|
|
- private void triggerReconnect() {
|
|
335
|
|
- coreExecutor.schedule(() -> {
|
|
336
|
|
- int maxAttempts = 3;
|
|
337
|
|
- int attempt = 1;
|
|
338
|
|
- while (attempt <= maxAttempts && !isConnected.get()) {
|
|
339
|
|
- try {
|
|
340
|
|
- log.info("MQTT 重连(第" + attempt + "次)");
|
|
341
|
|
- if (connectAndSubscribe(currentTopicSet)) {
|
|
342
|
|
- log.info("MQTT 重连成功");
|
|
343
|
|
- break;
|
|
344
|
|
- }
|
|
345
|
|
- attempt++;
|
|
346
|
|
- if (attempt <= maxAttempts) Thread.sleep(RECONNECT_INTERVAL * 2 * attempt);
|
|
347
|
|
- } catch (InterruptedException e) {
|
|
348
|
|
- Thread.currentThread().interrupt();
|
|
349
|
|
- break;
|
|
350
|
|
- } catch (Exception e) {
|
|
351
|
|
- log.error("MQTT 重连失败(第" + attempt + "次):" + e.getMessage());
|
|
352
|
|
- attempt++;
|
|
353
|
|
- }
|
|
354
|
|
- }
|
|
355
|
|
- if (attempt > maxAttempts) {
|
|
356
|
|
- log.error("MQTT 重连达最大次数,停止尝试");
|
|
357
|
|
- isConnected.set(false);
|
|
358
|
|
- }
|
|
359
|
|
- }, 5, TimeUnit.SECONDS);
|
|
360
|
|
- }
|
|
361
|
|
-
|
|
362
|
|
- private boolean checkServerAvailability() {
|
|
363
|
|
- try (Socket socket = new Socket()) {
|
|
364
|
|
- socket.setSoTimeout(CONNECT_TIMEOUT);
|
|
365
|
|
- socket.setTcpNoDelay(true);
|
|
366
|
|
- socket.connect(new InetSocketAddress(brokerHost, brokerPort), CONNECT_TIMEOUT);
|
|
367
|
|
- return true;
|
|
368
|
|
- } catch (Exception e) {
|
|
369
|
|
- log.error("MQTT Broker 不可达:" + e.getMessage());
|
|
370
|
|
- return false;
|
|
371
|
|
- }
|
|
372
|
|
- }
|
|
373
|
|
-
|
|
374
|
|
- private String generateUniqueClientId() {
|
|
375
|
|
- String osPrefix = System.getProperty("os.name").toLowerCase().contains("windows") ? "mqtt_win_" : "mqtt_linux_";
|
|
376
|
|
- return osPrefix + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
|
377
|
|
- }
|
|
378
|
|
-
|
|
379
|
|
- private void setMqttCallback() {
|
|
380
|
|
- if (mqttClient == null) return;
|
|
381
|
|
- mqttClient.setCallback(new MqttCallback() {
|
|
382
|
|
- @Override
|
|
383
|
|
- public void connectionLost(Throwable cause) {
|
|
384
|
|
- log.error("MQTT 连接断开:" + cause.getMessage());
|
|
385
|
|
- isConnected.set(false);
|
|
386
|
|
- coreExecutor.schedule(() -> triggerReconnect(), 5, TimeUnit.SECONDS);
|
|
387
|
|
- }
|
|
388
|
|
-
|
|
389
|
|
- @Override
|
|
390
|
|
- public void messageArrived(String topic, MqttMessage message) {
|
|
391
|
|
- // 直接提交到写入线程池处理
|
|
392
|
|
- writeExecutor.submit(() -> {
|
|
393
|
|
- try {
|
|
394
|
|
- String content = new String(message.getPayload(), StandardCharsets.UTF_8);
|
|
395
|
|
- if (content == null || content.trim().isEmpty()) return;
|
|
396
|
|
-
|
|
397
|
|
- Map<String, Object> messageMap = objectMapper.readValue(content, new TypeReference<Map<String, Object>>() {});
|
|
398
|
|
- processMessageAndWriteToTDengine(messageMap, topic);
|
|
399
|
|
- } catch (Exception e) {
|
|
400
|
|
- log.error("MQTT 消息处理失败(Topic:" + topic + "):", e);
|
|
401
|
|
- }
|
|
402
|
|
- });
|
|
403
|
|
- }
|
|
404
|
|
-
|
|
405
|
|
- @Override
|
|
406
|
|
- public void deliveryComplete(IMqttDeliveryToken token) {
|
|
407
|
|
- try { token.waitForCompletion(1000); } catch (MqttException ignored) {}
|
|
408
|
|
- }
|
|
409
|
|
- });
|
|
|
52
|
+ @Override
|
|
|
53
|
+ protected void processMessage(String content, String topic) throws Exception {
|
|
|
54
|
+ Map<String, Object> weather = objectMapper.readValue(content, new TypeReference<Map<String, Object>>() {});
|
|
|
55
|
+ processMessageAndWriteToTDengine(weather, topic);
|
|
|
56
|
+ insertredis(weather, topic);
|
|
410
|
57
|
}
|
|
411
|
58
|
|
|
412
|
59
|
private void processMessageAndWriteToTDengine(Map<String, Object> weather, String topic) throws Exception {
|
|
|
@@ -433,7 +80,6 @@ public class MqttDynamicConsumer {
|
|
433
|
80
|
list.put("timestamp", weather.get("timestamp"));
|
|
434
|
81
|
list.put("device_id", weather.get("device_id"));
|
|
435
|
82
|
|
|
436
|
|
- // 构建单条数据并立即写入(可改为批量缓冲)
|
|
437
|
83
|
String dbName = topicParts[0];
|
|
438
|
84
|
String superTable = topicParts[1];
|
|
439
|
85
|
LocalDate date = LocalDate.now();
|
|
|
@@ -441,16 +87,13 @@ public class MqttDynamicConsumer {
|
|
441
|
87
|
|
|
442
|
88
|
List<Map<String, Object>> batch = Collections.singletonList(list);
|
|
443
|
89
|
tdengineService.insertBatch(dbName, tableName, batch);
|
|
444
|
|
- insertredis(weather,topic);
|
|
445
|
90
|
}
|
|
446
|
91
|
|
|
447
|
|
-
|
|
448
|
92
|
public void insertredis(Map<String, Object> weather, String topic) throws Exception {
|
|
449
|
93
|
String[] topicParts = topic.split("/", 2);
|
|
450
|
94
|
if (topicParts.length < 2) return;
|
|
451
|
95
|
|
|
452
|
96
|
String controllerId = topicParts[0];
|
|
453
|
|
- String deviceIdFromTopic = topicParts[1]; // 虽然不用在 key 中,但可记录
|
|
454
|
97
|
|
|
455
|
98
|
SysController sysController = sysControllerService.selectcontrollerpath(topic);
|
|
456
|
99
|
if (sysController == null || sysController.getName() == null) return;
|
|
|
@@ -461,14 +104,12 @@ public class MqttDynamicConsumer {
|
|
461
|
104
|
Map<String, Object> metricData = (Map<String, Object>) weather.get(sysController.getName());
|
|
462
|
105
|
if (metricData == null) return;
|
|
463
|
106
|
|
|
464
|
|
- // ✅ 使用标准格式:DSB:controllerId:metricName
|
|
465
|
107
|
String redisKey = "DSB:" + controllerId + ":" + sysController.getName();
|
|
466
|
108
|
|
|
467
|
|
- // 准备写入的数据(包含系统字段)
|
|
468
|
109
|
Map<String, String> hashData = new HashMap<>();
|
|
469
|
110
|
hashData.put("createTime", createTime);
|
|
470
|
111
|
hashData.put("timestamp", getStringFromMap(weather, "timestamp"));
|
|
471
|
|
- hashData.put("device_id", getStringFromMap(weather, "device_id")); // UUID
|
|
|
112
|
+ hashData.put("device_id", getStringFromMap(weather, "device_id"));
|
|
472
|
113
|
|
|
473
|
114
|
for (Map.Entry<String, Object> entry : metricData.entrySet()) {
|
|
474
|
115
|
if (entry.getValue() != null) {
|
|
|
@@ -479,7 +120,6 @@ public class MqttDynamicConsumer {
|
|
479
|
120
|
stringRedisTemplate.opsForHash().putAll(redisKey, hashData);
|
|
480
|
121
|
stringRedisTemplate.expire(redisKey, 2, TimeUnit.HOURS);
|
|
481
|
122
|
|
|
482
|
|
- // 记录到活跃集合
|
|
483
|
123
|
stringRedisTemplate.opsForSet().add("DSB:active:devices", redisKey);
|
|
484
|
124
|
stringRedisTemplate.expire("DSB:active:devices", 2, TimeUnit.HOURS);
|
|
485
|
125
|
}
|
|
|
@@ -488,51 +128,4 @@ public class MqttDynamicConsumer {
|
|
488
|
128
|
Object val = map.get(key);
|
|
489
|
129
|
return val == null ? "" : val.toString().trim();
|
|
490
|
130
|
}
|
|
491
|
|
-
|
|
492
|
|
-
|
|
493
|
|
-
|
|
494
|
|
- private Map<String, Object> deepCopyMap(Map<String, Object> original) {
|
|
495
|
|
- if (original == null) return new HashMap<>();
|
|
496
|
|
- try {
|
|
497
|
|
- String json = objectMapper.writeValueAsString(original);
|
|
498
|
|
- return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
|
|
499
|
|
- } catch (Exception e) {
|
|
500
|
|
- Map<String, Object> copy = new HashMap<>(original.size());
|
|
501
|
|
- original.forEach((k, v) -> {
|
|
502
|
|
- if (v instanceof Map) {
|
|
503
|
|
- copy.put(k, deepCopyMap((Map<String, Object>) v));
|
|
504
|
|
- } else {
|
|
505
|
|
- copy.put(k, v);
|
|
506
|
|
- }
|
|
507
|
|
- });
|
|
508
|
|
- return copy;
|
|
509
|
|
- }
|
|
510
|
|
- }
|
|
511
|
|
-
|
|
512
|
|
- public void disconnect() {
|
|
513
|
|
- synchronized (lock) {
|
|
514
|
|
- if (mqttClient != null) {
|
|
515
|
|
- try {
|
|
516
|
|
- if (mqttClient.isConnected()) {
|
|
517
|
|
- unsubscribeAll();
|
|
518
|
|
- mqttClient.disconnect(10000);
|
|
519
|
|
- }
|
|
520
|
|
- mqttClient.close();
|
|
521
|
|
- log.info("MQTT 连接已断开");
|
|
522
|
|
- } catch (MqttException e) {
|
|
523
|
|
- log.error("断开 MQTT 连接失败:" + e.getMessage());
|
|
524
|
|
- } finally {
|
|
525
|
|
- isConnected.set(false);
|
|
526
|
|
- mqttClient = null;
|
|
527
|
|
- }
|
|
528
|
|
- }
|
|
529
|
|
- if (tdengineService != null) tdengineService.close();
|
|
530
|
|
- }
|
|
531
|
|
- }
|
|
532
|
|
-
|
|
533
|
|
- @PreDestroy
|
|
534
|
|
- public void destroy() {
|
|
535
|
|
- log.info(">>> 服务正在关闭...");
|
|
536
|
|
- disconnect();
|
|
537
|
|
- }
|
|
538
|
|
-}
|
|
|
131
|
+}
|