MQTT
MQTT-Eclipse paho mqtt重连机制
- 代码样例
- 代码解析
- 设置重连
- 问题说明
代码样例
import org.eclipse.paho.client.mqttv3.*;public class ConnectMQTT {public void connectMQtt() throws MqttException {MqttConnectOptions options = new MqttConnectOptions();//心跳时间限定为30至1200秒options.setKeepAliveInterval(120);options.setConnectionTimeout(5000);options.setAutomaticReconnect(true);options.setUserName("username");options.setPassword("password".toCharArray());/*设置重连*/options.setAutomaticReconnect(true);IMqttClient client = new MqttClient("url", "clientId");client.setCallback(callback);// 建立连接client.connect(options);}private static MqttCallback callback = new MqttCallbackExtended() {/*** 连接成功回调-可以在重新连接成功时,重新订阅topic* @param reconnect* @param serverURI*/@Overridepublic void connectComplete(boolean reconnect, String serverURI) {System.out.println("Mqtt client connected. address:" + serverURI);}@Overridepublic void connectionLost(Throwable cause) {cause.printStackTrace();System.out.println("Connection lost.");}/*** 接受消息处理* @param topic* @param message* @throws Exception*/@Overridepublic void messageArrived(String topic, MqttMessage message) throws Exception {System.out.println("Receive mqtt topic:" + topic + ", message:" + message);}@Overridepublic void deliveryComplete(IMqttDeliveryToken token) {System.out.println("Mqtt message deliver complete.");}};}
代码解析
设置重连
需要设置automaticReconnect为true,默认是不支持重连机制的,当设置为true时,当连接断开时,会进行重新。客户端将尝试重新连接到服务器。它一开始会等待1秒它尝试重新连接,对于每一次失败的重新连接尝试,延迟将加倍直到它在2分钟,此时延迟将停留在2分钟
/*
设置重连*/
options.setAutomaticReconnect(true);
问题说明
1、在开发时设置automaticReconnect未true,重新连接成功后,会丢失订阅相关信息。
原因:因cleanSession参数默认为true,在重连成功后,会丢失订阅消息。
修改:可以将cleanSession参数设置为false,也可以在重连成功后重新订阅topic
我则是在重连成功时重新订阅topic。