1、消息保留
当客户端连接时将 Retained 为 true ,Broker 会存储每个 Topic 的最后一条保留消息及其 Qos,当订阅该 Topic 的客户端上线后,Broker 需要将该消息投递给它。
- 保留消息作用:
可以让新订阅的客户端得到发布方的最新的状态值,而不必等待新消息推送。 - 保留消息弊端:
Broker保存的消息会与断线重连接收的断线消息重复。且每次重连时都会投递一次。 - 保留消息的删除:
发送一条Retained为true,payload为空的消息即可解除。
/**
* 删除 发送给 topic 主题的保留消息
*/
private static String topic;
public static void main(String[] age){
try {
MqttClient client = new MqttClient( serverUrl,clientId,new MemoryPersistence());
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(true);
mqttConnectOptions.setUserName(userName);
mqttConnectOptions.setPassword(password.toCharArray());
// message 的 payload 必须为空(不设置即可)
MqttMessage mqttMessage = new MqttMessage();
mqttMessage.setQos(1);
// retained 必须设置为 true
mqttMessage.setRetained(true);
client.connect(mqttConnectOptions);
client.publish(topic,mqttMessage);
client.disconnect();
client.close();
} catch (MqttException e) {
e.printStackTrace();
}
}
2、遗嘱消息
遗嘱消息是在客户端 connect 时候,在 MqttConnectOptions 里面的 will 预先设定好的,用于在客户端断开连接

探讨MQTT协议中遗嘱消息与消息保留机制的作用、弊端及应用,通过实例展示如何利用这两种特性监控设备在线状态,减少延迟并提高程序性能。
最低0.47元/天 解锁文章
620





