2021与蓝度共同重构项目,服务端
liuhaonan
2022-11-18 b531004a3cbd33d7bb9f5b7dce06ddd4f5e7ec9a
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.sandu.ximon.admin.localMQTT.callback;
 
import com.sandu.ximon.admin.localMQTT.client.MqttClientManager;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
 
/**
 * @author van
 * @version 1.0
 * msg:MQTT回调抽象类
 * @date 2022/11/9 16:23
 */
@Slf4j
public abstract class AbsMqttCallBack implements MqttCallback {
    private String clientId;
    private MqttConnectOptions connectOptions;
 
    public String getClientId() {
        return clientId;
    }
 
    public void setClientId(String clientId) {
        this.clientId = clientId;
    }
 
    public MqttConnectOptions getConnectOptions() {
        return connectOptions;
    }
 
    public void setConnectOptions(MqttConnectOptions connectOptions) {
        this.connectOptions = connectOptions;
    }
 
    /**
     * 失去连接操作,进行重连
     *
     * @param throwable 异常
     */
    @Override
    public void connectionLost(Throwable throwable) {
        try {
            if (null != clientId) {
                if (null != connectOptions) {
                    MqttClientManager.getInstance().getMqttClientById(clientId).connect(connectOptions);
                } else {
                    MqttClientManager.getInstance().getMqttClientById(clientId).connect();
                }
            }
 
        } catch (Exception e) {
            log.error("{} reconnect failed!", e);
        }
    }
 
    /**
     * 接收订阅消息
     *
     * @param topic           主题
     * @param mqttMessage 接收消息
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) {
        String content = new String(mqttMessage.getPayload());
        log.info("Receive topic[{}],message={}", topic, content);
        handleReceiveMessage(topic, content);
    }
 
    /**
     * 消息发送成功
     *
     * @param iMqttDeliveryToken toke
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("消息发送成功");
    }
 
 
    /**
     * 处理接收的消息
     *
     * @param topic   主题
     * @param message 消息内容
     */
    protected abstract void handleReceiveMessage(String topic, String message);
}