【发布时间】:2018-10-18 12:04:35
【问题描述】:
我正在使用 Eclipse Paho 实现 MQTT 客户端,但遇到了一些问题:
发布者和订阅者都使用 qos = 1 和 setCleanSession = 连接到代理 假的。
我的流程:
- 将订阅者和发布者连接到代理,没关系。
- 断开订阅者(我强制停止包含订阅者的我的项目),发布者继续发布消息。
- 重新连接订阅者 -> 无法连接并抛出异常:connectionLost。
如果我设置订阅者的 qos = 0,它不会抛出异常,但客户端在订阅者离线时不会收到发布者发送的消息,这是我不想要的
有人可以帮我解决这个问题吗?
这是我在订阅者中的代码
try {
// Create an Mqtt client
MqttAsyncClient mqttClient
= new MqttAsyncClient("tcp://" + swmConfig.getMqttApiLink(), "MeasureTransactionApi");
// new MqttAsyncClient(serverURI, clientId, persistence)
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setUserName(swmConfig.getMqttUsername());
connOpts.setPassword(swmConfig.getMqttPassword().toCharArray());
connOpts.setCleanSession(false);
// Connect to RabbitMQ Broker
log.info("Connecting to RabbitMQ broker: " + swmConfig.getMqttApiLink());
IMqttToken conToken = mqttClient.connect(connOpts);
conToken.waitForCompletion(10000);
if (!conToken.isComplete() || conToken.getException() != null) {
log.info("Error connecting: " + conToken.getException());
System.exit(-1);
}
log.info("Connected");
// Latch used for synchronizing b/w threads
final CountDownLatch latch = new CountDownLatch(1);
// Callback - Anonymous inner-class for receiving messages
mqttClient.setCallback(new MqttCallback() {
public void messageArrived(String topic, MqttMessage message) {
String time = new Timestamp(System.currentTimeMillis()).toString();
log.info("\nReceived a Message from RabbitMQ Broker" + "\n\tTime: " + time
+ "\n\tTopic: " + topic + "\n\tMessage: "
+ new String(message.getPayload()) + "\n\tQoS: "
+ message.getQos() + "\n");
handleMQTTMessageService.handleMessageArrived(message);
}
public void connectionLost(Throwable cause) {
log.info("Connection to RabbitMQ broker lost!" + cause.getMessage());
latch.countDown();
}
public void deliveryComplete(IMqttDeliveryToken token) {
log.info("deliveryComplete");
}
});
// Subscribe client to the topic filter with QoS level of 1
log.info("Subscribing client to topic: " + topic);
IMqttToken subToken = mqttClient.subscribe(topic, 1);
subToken.waitForCompletion(10000);
if (!subToken.isComplete() || subToken.getException() != null) {
log.info("Error subscribing: " + subToken.getException());
System.exit(-1);
}
} catch (MqttException me) {
log.error("Error:", me);
}
【问题讨论】:
-
QoS = 0 不会重试或确保交付。检查文档。 hivemq.com/blog/…
-
谢谢尼古拉斯。我明白那个。现在我有另一个问题。当 qos = 1 时,有时代理不会发布所有订阅消息。代理中留下了一些消息,并且未确认。不知道订阅者有没有收到消息?
-
如果您有新问题,请提出一个新问题,并将任何适当的答案标记为已接受。这不是一个辅导网站。