MQTT 基于mqttv3 客户端重连配置

需求:

        当mqtt服务器或客户端发生网络问题,导致客户端不可用,出现了生产故障,导致设备离线,引发一系列的问题。为了解决这个问题,我们需求对mqtt客户端进行重连配置,对mqtt服务器进行故障检测,重启配置,实现程序的健壮性。

1.引入pom依赖

<dependency>
    <groupId>org.eclipse.paho</groupId>
    <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
    <version>1.2.1</version>
</dependency>

2.V1版本,通过设置(AutomaticReconnect) 进行断线重连,当服务端或客户端服务器网络故障(不可用),mqtt客户端不会进行重试连接

class TestV1{

    private MqttClient client = null;

    private void initMq() {
        String serverUri = "tcp://localhost:1883";
        String clientId = "MQTT-CLIENT";
        try {
            client = new MqttClient(serverUri, clientId, new MemoryPersistence());
        } catch (MqttException e) {
            return;
        }

        //客户端连接参数
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName("test");
        options.setPassword("test".toCharArray());
        options.setConnectionTimeout(30);
        options.setKeepAliveInterval(60);
        //设置自动重连
        options.setAutomaticReconnect(true);
        
        //设置回调
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                // no need rec
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                if (!token.isComplete()) {
                }
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {

            }
        });

        try {
            client.connect(options);

            subscribe();

        } catch (MqttException e) {
            return;
        }
    }

    private void subscribe(){
        try {
            //订阅队列
            client.subscribe("test_topic", 2, (topic, message) -> {
                String msg = new String(message.getPayload(), StandardCharsets.UTF_8);
            });
        } catch (MqttException e) {
            return;
        }
    }
}

3.V2 版本,主动断开客户端(服务端)导致不可用,则会进行重试

class TestV2{

    private MqttClient client = null;

    private void initMq() {
        String serverUri = "tcp://localhost:1883";
        String clientId = "MQTT-CLIENT";
        try {
            client = new MqttClient(serverUri, clientId, new MemoryPersistence());
        } catch (MqttException e) {
            return;
        }

        //客户端连接参数
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName("test");
        options.setPassword("test".toCharArray());
        options.setConnectionTimeout(30);
        options.setKeepAliveInterval(60);
        //设置自动重连
        options.setAutomaticReconnect(true);

        //设置回调
        client.setCallback(new MqttCallbackExtended() {
            //连接成功回调,需要重新订阅主题
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                sendNotify(true);
                subscribe();
            }
            //连接异常,进行重连
            @Override
            public void connectionLost(Throwable cause) {
                retryConnection(3);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                if (!token.isComplete()) {
                }
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
            }
        });

        try {
            client.connect(options);

            subscribe();

        } catch (MqttException e) {
            return;
        }
    }

    private void subscribe(){
        try {
            //订阅队列
            client.subscribe("test_topic", 2, (topic, message) -> {
                String msg = new String(message.getPayload(), StandardCharsets.UTF_8);
                //处理消息
            });
        } catch (MqttException e) {
            return;
        }
    }

    private   void retryConnection(int retryNumber){
        //当重试多次,依旧失败,就是机器故障,需要通知人工处理
        if(retryNumber< 0){
            sendNotify(false);
            return;
        }
        try {
            client.reconnect();
            TimeUnit.SECONDS.sleep(30);
            if(!client.isConnected()){
                retryConnection(--retryNumber);
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }catch (InterruptedException e){
            e.printStackTrace();
        }

    }
    
    private void sendNotify(boolean isSuccess){
        //发送重试通知
    }
}

4.说明

MqttCallbackExtended是MqttCallback增强,增加了连接成功的回调 。

以上是通过实际生产中实践得出的经验。想要了解更多的细节可以查看源码实现。

如有理解不当的地方,欢迎大家指出。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在Spring Boot应用中使用MQTT协议,可以使用Eclipse Paho MQTT客户端库。以下是基于Spring Boot的MQTT连接的步骤: 1. 添加Maven依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId> <version>1.2.5</version> </dependency> ``` 2. 配置application.properties 在application.properties文件中添加MQTT连接相关的配置: ``` mqtt.server.uri=tcp://localhost:1883 mqtt.client.id=myClient mqtt.topic=test/topic mqtt.qos=1 ``` 其中,mqtt.server.uri表示MQTT服务器的URI地址,mqtt.client.id表示客户端ID,mqtt.topic表示要订阅的主题,mqtt.qos表示消息的质量。 3. 创建MQTT客户端 在Spring Boot应用程序中创建MQTT客户端,可以使用以下代码: ```java @Autowired private MqttClient mqttClient; @Value("${mqtt.server.uri}") private String serverURI; @Value("${mqtt.client.id}") private String clientId; @PostConstruct public void init() { try { mqttClient = new MqttClient(serverURI, clientId); } catch (MqttException e) { e.printStackTrace(); } } ``` 4. 订阅主题 使用以下代码订阅主题: ```java try { mqttClient.subscribe(topic, qos); } catch (MqttException e) { e.printStackTrace(); } ``` 其中,topic是要订阅的主题,qos表示消息质量。 5. 发布消息 使用以下代码发布消息: ```java try { MqttMessage message = new MqttMessage(); message.setPayload(payload.getBytes()); message.setQos(qos); mqttClient.publish(topic, message); } catch (MqttException e) { e.printStackTrace(); } ``` 其中,payload是要发布的消息内容,qos表示消息质量,topic表示要发布的主题。 这样,就可以在Spring Boot应用程序中使用MQTT协议连接到MQTT服务器,并订阅和发布MQTT消息了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值