.mqttv3支持 MqttClient (同步)、MqttAsyncClient(异步),官方建议使用异步实现,使用返回的token追踪状态,并可以使用 token.waitForCompletion(); 阻塞进程,直到操作完成,
但是请留意,官网有真么一句话:
If a client connects with cleanSession true then there will be no delivery tokens as the cleanSession option deletes all earlier state. For state to be remembered the client must connect with cleanSession set to false
(如果客户端连接到cleanSession true,则不会有任何交付令牌,因为cleanSession选项会删除所有之前的状态。若要记住状态,客户端必须与设为false的清洁状态连接)
这样获取的只是正在发布的所有token,不包含其他token
发布时可以将进程阻塞,同时
// 方法1:if (mqttConnectOptions.getMaxInflight() - mqttAscClient.getInFlightMessageCount() > 0)
//方法2:if (mqttConnectOptions.getMaxInflight() - mqttAscClient.getPendingDeliveryTokens().length > 0)
获取正在进行的发布数,如果小于设置的最大发布数,就可以进行新的发布。
方法1:getInFlightMessageCount 只是待队列中的消息数,不是真正发送的消息,必须要保证发送是同步的,使用方法2可以异步发送,
//publish 方法 token.waitForCompletion();可以省略
而方法2:获取的是确切的正在进行的发布,有确定的唯一token
建议使用方法2.
==================================================================================
如果认为这篇文章帮到了你,那就请领个红包打赏下吧