zhubaomin
2025-02-17 b029979db841167a3b2b403fdb24dfbf5ffce615
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
package com.dy.pipIrrApp.workOrder.mqtt;
 
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
 
/**
 * @author ZhuBaoMin
 * @date 2024-11-16 11:29
 * @LastEditTime 2024-11-16 11:29
 * @Description 初始化一个Mqtt客户端,并根据配置订阅topic
 */
 
@Slf4j
public class MqttMsgSubscriber {
 
    public void readSubscribeTopicMessage(){
        try {
            //String broker = "tcp://127.0.0.1:1883";
            //String username = "mqtt_u";
            //String password = "yjy";
            //String topic = "workOrder";
            String broker = "tcp://127.0.0.1:1884";
            String username = "server";
            String password = "1234";
            String topic = "report/#";
 
            Integer qos = 2;
            String clientId = System.currentTimeMillis() + "";
 
            MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence());
 
            // 连接参数
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            //是否清除会话
            options.setCleanSession(true);
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            client.setCallback(new MqttCallback() {
 
                @Override
                public void connectionLost(Throwable throwable) {
                    log.error("连接丢失");
                }
 
                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    log.info("topic为: " + topic);
                    log.info("qos为: " + mqttMessage.getQos());
                    log.info("消息内容为: " + new String(mqttMessage.getPayload()));
                }
 
                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    // 当消息被完全传送出去后调用
                    log.info("交付完成 ---Delivery complete!");
                    // 可以在这里处理一些发送完成后的清理工作
                }
            });
 
            client.connect(options);
            client.subscribe(topic, qos);
        } catch (MqttException e){
            log.error("MqttMsgSubscriber 连接启动异常:{}", e.getMessage());
        } catch (Exception e){
            log.error("MqttMsgSubscriber 读取消息异常:{}", e.getMessage());
        }
    }
}