eclipse paho mqtt client 使用一些注意点

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

broker 用的是 emqttd,开源版本的。 broker端虽然记录了session,但是没有持久化session所以

如果broker遇到问题重启了,所有的 client端都得重启,因为服务端丢失了client 的 subscribe信息。(即使cleanSession=false)。为了避免服务端重启、网络短时断线影响消息的持续接收,需要做一些设置和编码。如下:

 

解决方式,是  

1. 设置 autoreconnect=true

2. 设置connect callback,监听 connect lost 事件,然后调用 reconnect 方法,connect complete后再重新subscribe

3. 设置 connectionTimeout = 0

(cleanSession=false即可)

具体:

 connOpts.setAutomaticReconnect(true);    //mqttClient.reconnect(); 方法会判断这个参数
 connOpts.setConnectionTimeout(0);  //防止 ERROR o.e.p.c.mqttv3.internal.ClientState - Timed out as no activity  错误
 connOpts.setCleanSession(false);  //服务端记录 session (自己手动重新subscribe ,可能设置为true也行)

    @PostConstruct
	public void startSubscribe() {

		mqttClient.setCallback(new MqttCallbackExtended() {

			@Override
			public void connectionLost(Throwable cause) {
				try {
					mqttClient.reconnect();
				} catch (MqttException e) {
					LOG.error(e.getMessage(), e);
				}
			}

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

			@Override
			public void deliveryComplete(IMqttDeliveryToken token) {
			}

			@Override
			public void connectComplete(boolean reconnect, String serverURI) {
				startSubscribe();
			}

		});

		try {
			
			mqttClient.subscribe(gatewayPrefix + "#", 0, new IMqttMessageListener() { // + HASH

				/**
				 * 
				 * 注意:这个方法完成后,mqttClient 才会回发确认,
				 * 所以其实采用QoS 1的时候,解析和持久化在这个方法里面实现就可以了。 但是我们现在 持久化是
				 * 异步的。 现在约定是 QoS 0. mqtt 本身不回发确认
				 * 
*/ @Override public void messageArrived(String topic, MqttMessage message) throws Exception { try { String json = new String(message.getPayload()); LOG.debug("Recived data topic[{}], payload[{}]", topic, json); mqttDataDispatcher.dispatcher(topic, json); } catch (Exception e) { LOG.error(e.getMessage(), e); } } }); } catch (MqttException e) { LOG.error("mqtt subscribe exception", e); if (mqttClient.isConnected()) { LOG.info("will re-subscribe..."); startSubscribe(); } } }

 

转载于:https://my.oschina.net/chen1988/blog/1604369

你可能感兴趣的:(eclipse paho mqtt client 使用一些注意点)