2021与蓝度共同重构项目,服务端
Van333
2022-12-05 694d691291f6ee89061fdbb9fd451ecb5519b69b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.sandu.ximon.admin.localMQTT.client;
 
import com.sandu.ximon.admin.localMQTT.config.MqttConfig;
import com.sandu.ximon.admin.localMQTT.model.MqttClientVO;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import java.util.List;
 
/**
 * @author van
 * @version 1.0
 * msg:
 * @date 2022/11/29 13:46
 */
@Slf4j
@EnableScheduling
@Component
public class KeepEMQXClient {
 
    @Autowired
    private MqttConfig mqttConfig;
 
    @Resource
    private MqttClientManager mqttClientManager;
 
    @Scheduled(cron = "*/30 * * * * * ")
    public void keepClient()  {
 
        List<MqttClientVO> mqttClientList = mqttConfig.getClientList();
        for (MqttClientVO mqttClientVO : mqttClientList) {
            //创建客户端,客户端ID:demo,回调类跟客户端ID一致
            MqttClient mqttClient = MqttClientManager.getInstance().getMqttClientById(mqttClientVO.getClientId());
 
            if (null == mqttClient) {
                log.error("Not exist mqttClient where it's clientId is {}", mqttClientVO.getClientId());
                mqttClientManager.createMqttClient(mqttClientVO.getClientId(), mqttClientVO.getSubscribeTopic(), mqttClientVO.getUserName(), mqttClientVO.getPassword());
                System.out.println(mqttClient.getClientId() + "重新创建完成");
 
            }
            else {
                try {
                    mqttClient.publish("v1/devices/keepAlive", new MqttMessage() );
                } catch (MqttException e) {
                    log.error("mqttClient.getClientId()..发送消息失败...........");
                    mqttClientManager.createMqttClient(mqttClientVO.getClientId(), mqttClientVO.getSubscribeTopic(), mqttClientVO.getUserName(), mqttClientVO.getPassword());
                    log.error("创建."+mqttClient.getClientId()+".成功...........");
                }
            }
        }}
 
 
}