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 预先设定好的,用于在客户端断开连接后向 Broker 发送的最后一条消息。

以下情况下会发送 Will Message:

  • 服务端发生了I/O 错误或者网络失败;
  • 客户端在定义的心跳时期失联;
  • 客户端在发送下线包之前关闭网络连接;
  • 服务端在收到下线包之前关闭网络连接。

Will Message 分别有 4 个参数:

  • topic :预定发布的主题,当客户端断线都订阅该主题的客户端都会收到一条遗嘱消息
  • payload:遗嘱消息内容
  • qos:遗嘱消息质量
  • retained:遗嘱消息是否保留
/**
     * 连接客户端 并设置向 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());
            try {
                // 设置遗嘱消息,并保留
               mqttConnectOptions.setWill(topic,"offline".getBytes("UTF-8"),1,true);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            
            client.connect(mqttConnectOptions);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

3、遗嘱消息及消息保留的应用

在 MQTT 的使用场景里经常会有监控底下设备的在线情况,正常我们处理方式都是在被监测方实时发送在线心跳包,在监测方实时判断最后在线时间,这样就会有一定滞后性,并且程序上还需要花费一定性能去处理数据传输和处理。

使用遗嘱消息和消息保留就可以很完美的实现这一需求。

我们在客户端连接时设置客户端下线遗嘱消息并保留,在连接成功后向 topic 主题发送一条客户端上线通知,并设置消息保留。

private static String topic;
    // 服务器连接参数一般写在配置文件中
    private static String host;
    private static String userName;
    private static String password;
    /**
     * 创建客户端
     */
    public static boolean createClient(){
        // 创建客户端, MemoryPersistence 设置 client 的保存方式默认以内存保存
        // clientId 是客户端的唯一标识, 相同的 clientId 客户端连接时会导致已连接的客户端断开连接
        String clientId = "clientId";
        try {
            MqttClient  client = new MqttClient(host,clientId,new MemoryPersistence());
            // 设置回调函数
            client.setCallback(new MqttCallbackExtended(){
                /**
                 * todo 本文重点 在连接成功回调函数中 向 topic 主题发送客户端上线通知
                 * @param b
                 * @param s
                 */
                @Override
                public void connectComplete(boolean b, String s) {
                    System.out.println("[MQTT Service] 连接已完成...");
                    // 连接完成可以做一些初始化操作
                    MqttMessage mqttMessage = new MqttMessage();
                    mqttMessage.setQos(1);
                    // 设置消息保留
                    mqttMessage.setRetained(true);
                    try {
                        mqttMessage.setPayload("online".getBytes("UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    try {
                        client.publish(topic,mqttMessage);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("[MQTT Service] 连接已断开...");
                    // 不设置断线自动连接时,可在这边自定义重连
                }


                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("[MQTT Service] 数据已到达...");
                    String content = new String(message.getPayload(),"UTF-8");
                    System.out.println("【MQTT】订阅主题:" + topic);
                    System.out.println("【MQTT】订阅质量:" + message.getQos());
                    System.out.println("【MQTT】订阅内容:" + content);
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("[MQTT Service] 数据传送成功...");
                }
            });
            MqttConnectOptions connectOptions = new MqttConnectOptions();
            // 设置是否关闭连接会话
            // 设置为 true 时,客户端每次都会以新的身份连接
            // 设置为 false 时,客户端再次连接会继续之前的会话,再次连接后无需再次订阅即可收到之前已订阅过的主题消息,包括断线后发布的消息。 
            // 设置为 false 有个前置条件就是 clientId 不变
            connectOptions.setCleanSession(true);
            connectOptions.setUserName(userName);
            connectOptions.setPassword(password.toCharArray());
            // 断线后是否自动重连
            connectOptions.setAutomaticReconnect(false);
            try {
                // todo 本文重点 设置遗嘱消息,并保留
                connectOptions.setWill(topic,"offline".getBytes("UTF-8"),1,true);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // 客户端重复连接不会导致重复订阅和发布
            try {
                client.connect(connectOptions);
            } catch (MqttException e) {
                System.out.println("客户端连接失败!"+ e.getMessage());
                return false;
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
        
        return true;
    }

这样设置完无论订阅者什么时候来,都能拿到第一手客户端在线状态,并且无需客户端实时发送心跳包,提高程序性能。