Mqtt精髓系列之保留消息Retained Messages
翻译:https://www.hivemq.com/blog/mqtt-essentials-part-8-retained-messages
保留消息定义
如果PUBLISH消息的RETAIN标记位被设置为1,则称该消息为“保留消息”;
Broker对保留消息的处理
Broker会存储每个Topic的最后一条保留消息及其Qos,当订阅该Topic的客户端上线后,Broker需要将该消息投递给它。
A retained message is a normal MQTT message with the retained flag set to true. The broker will store the last retained message and the corresponding QoS for that topic Each client that subscribes to a topic pattern, which matches the topic of the retained message, will receive the message immediately after subscribing. For each topic only one retained message will be stored by the broker.
保留消息作用
可以让新订阅的客户端得到发布方的最新的状态值,而不必要等待发送。
A retained message makes sense, when newly connected subscribers should receive messages immediately and shouldn’t have to wait until a publishing client sends the next message. This is extremely helpful when for status updates of components or devices on individual topics. For example the status of device1 is on the topic myhome/devices/device1/status, a new subscriber to the topic will get the status (online/offline) of the device immediately after subscribing when retained messages are used. The same is true for clients, which send data in intervals, temperature, GPS coordinates and other data. Without retained messages new subscribers are kept in the dark between publish intervals. So using retained messages helps to provide the last good value to a connecting client immediately.
保留消息的删除
- 方式1:发送空消息体的保留消息;
- 方式2:发送最新的保留消息覆盖之前的(推荐);