one . background
Why retained?
1. When a message is posted to MQTT Server time , We need to keep the latest messages to the server , In order to avoid losing the last latest message when subscribing ;
When the subscription consumer server reconnects MQTT Server time , Always get the latest news on the subject , At this time, we need to retained Set to true;
2. When a message is posted to MQ Server time , We don't need to keep the latest messages to the server ;
When the subscriber reconnects to the consumer MQTT Server time , Can't get the latest news on the subject , Only messages published after connection can be retrieved , At this time, we need to retained Set to false;
two . The solution is as follows :
Through the source code, we can set MqttMessage Class setRetained() set up retained attribute ;
MqttMessage message = new MqttMessage(payload); message.setQos(qos);
message.setRetained(retained); return this.publish(message);
notes : Restart after modification MQTT The server ;
three . Application scenario
1. Reconnect MQTT Service time , You do not need to receive the latest messages on this topic , set up retained by false;
2. Reconnect MQTT Service time , You need to receive the latest messages on this topic , set up retained by true;
Technology
Daily Recommendation