概述
微消息队列MQ for IoT在处理离线消息时,为了简化离线消息获取机制,微消息队列系统在客户端成功建立连接并通过权限校验后,会自动加载离线消息并下发到客户端,但是实际在使用过程中会出现消费端启动后迟迟无法获取离线消息的问题,本文主要介绍延迟消息的发送与接收环节需要注意的问题。
协议相关
注意在使用SDK进行离线消息的发送过程中需要特别注意QoS和cleanSession两个参数。
- QoS 指代消息传输的服务质量(主要针对发送端)
取值 | 1 | 2 | 3 |
---|---|---|---|
意义 | 最多分发一次 | 最多分发一次 | 仅分发一次 |
- cleanSession 建立 TCP 连接后是否关心之前状态(主要针对接收端)
true | false |
------- | ------- |
客户端再次上线时,将不再关心之前所有的订阅关系以及离线消息 | 客户端再次上线时,还需要处理之前的离线消息,而之前的订阅关系也会持续生效 |
为了处理的方便,对于处理离线消息的情况,建议不论是发送端还是接收端,参数都设置为:
QoS = 1
cleanSession = false
Java示例代码
Send Code
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.io.IOException;
import java.util.Date;
import static org.eclipse.paho.client.mqttv3.MqttConnectOptions.MQTT_VERSION_3_1_1;
public class MQTTSendMsg1 {
public static void main(String[] args) throws IOException {
final String broker ="tcp://******.mqtt.aliyuncs.com:1883";
final String acessKey ="******";
final String secretKey ="******";
final String topic ="******";
final String clientId ="GID_******@@@ClientID_device1";
String sign;
MemoryPersistence persistence = new MemoryPersistence();
try {
final MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
final MqttConnectOptions connOpts = new MqttConnectOptions();
System.out.println("Connecting to broker: " + broker);
sign = MacSignature.macSignature(clientId.split("@@@")[0], secretKey);
connOpts.setUserName(acessKey);
connOpts.setServerURIs(new String[] { broker });
connOpts.setPassword(sign.toCharArray());
connOpts.setCleanSession(false);
connOpts.setKeepAliveInterval(90);
connOpts.setAutomaticReconnect(true);
connOpts.setMqttVersion(MQTT_VERSION_3_1_1);
sampleClient.setCallback(new MqttCallbackExtended() {
public void connectComplete(boolean reconnect, String serverURI) {
System.out.println("connect success");
//连接成功,需要上传客户端所有的订阅关系
}
public void connectionLost(Throwable throwable) {
System.out.println("mqtt connection lost");
}
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
System.out.println("messageArrived:" + topic + "------" + new String(mqttMessage.getPayload()));
}
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("deliveryComplete:" + iMqttDeliveryToken.getMessageId());
}
});
sampleClient.connect(connOpts);
for (int i = 0; i < 5; i++) {
try {
String scontent = new Date()+"MQTT Test body" + i;
//此处消息体只需要传入 byte 数组即可,对于其他类型的消息,请自行完成二进制数据的转换
final MqttMessage message = new MqttMessage(scontent.getBytes());
message.setQos(1);//设置离线消息的情况
System.out.println(i+" pushed at "+new Date()+" "+ scontent);
sampleClient.publish(topic+"/notice/", message);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception me) {
me.printStackTrace();
}
}
}
Receive Code
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MQTTRecvMsg {
public static void main(String[] args) {
final String broker ="tcp://******.mqtt.aliyuncs.com:1883";
final String acessKey ="******";
final String secretKey ="******";
final String topic ="******";
final String clientId ="GID_******@@@ClientID_device2";
String sign;
MemoryPersistence persistence = new MemoryPersistence();
try {
final MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
final MqttConnectOptions connOpts = new MqttConnectOptions();
System.out.println("Connecting to broker: " + broker);
sign = MacSignature.macSignature(clientId.split("@@@")[0], secretKey);
final String[] topicFilters=new String[]{topic+"/notice/"};
final int[]qos={1};
connOpts.setUserName(acessKey);
connOpts.setServerURIs(new String[] { broker });
connOpts.setPassword(sign.toCharArray());
connOpts.setCleanSession(false);//设置确定是否继续接受离线消息
connOpts.setKeepAliveInterval(90);
connOpts.setAutomaticReconnect(true);
final ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
sampleClient.setCallback(new MqttCallbackExtended() {
public void connectComplete(boolean reconnect, String serverURI) {
System.out.println("connect success");
//连接成功,需要上传客户端所有的订阅关系
executorService.submit(new Runnable()
{
public void run()
{
try
{
sampleClient.subscribe(topicFilters, qos);
} catch(Exception me)
{
me.printStackTrace();
}
}
});
}
public void connectionLost(Throwable throwable) {
System.out.println("mqtt connection lost");
}
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
System.out.println("messageArrived:" + topic + "------" + new String(mqttMessage.getPayload()));
}
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("deliveryComplete:" + iMqttDeliveryToken.getMessageId());
}
});
//客户端每次上线都必须上传自己所有涉及的订阅关系,否则可能会导致消息接收延迟
sampleClient.connect(connOpts);
//每个客户端最多允许存在30个订阅关系,超出限制可能会丢弃导致收不到部分消息
sampleClient.subscribe(topicFilters,qos);
Thread.sleep(Integer.MAX_VALUE);
} catch (Exception me) {
me.printStackTrace();
}
}
}
特别注意:
离线消息生成需要一定的时间,因为推送的消息需要等待客户端的 ack 超时才会被判成离线消息,所以获取离线消息一般也需要订阅端等待一定的时间。