我有一个使用 mqtt 发布/订阅技术进行物联网的项目。经过研究,我决定使用 Mosquitto 和 Paho mqtt。
我使用默认配置通过 mosquitto 设置了 mqtt 代理。我尝试编写代码以连接到 mqtt 代理,然后每 2 分钟发布一次消息以从设备检索数据。我的项目已经运行了一段时间,然后在发布步骤中以某种方式卡住了。
我遇到的第一个问题是 MqttException: Too many publishes in progress
然后我找到了通过设置 setMaxInflight
来解决的方法。我设置为 1000,问题解决了。
在那之后,我遇到了另一个问题。客户端代码运行几个小时后,发布方法卡住了,再也没有返回,然后我的代码没有按预期工作。不知道为什么发布没有返回但是文档说
Delivers a message to the server at the requested quality of service and returns control once the message has been delivered.
我是 mqtt 的新手,所以我认为 mqtt 代理没有发回 ack 或 mqtt 代理有任何问题。之后,我找了一段时间后取消的方法,我找到了这个
mqttClient.setTimeToWait(20000);
我尝试过,它在 20 秒后按预期抛出超时异常,但在运行几个小时后,我又解决了旧问题 MqttException: Too many publishes in progress
。
我认为 setTimeToWait(20000)
只是抛出异常而没有在飞行过程中取消,所以它达到了 1000,我设置了 MaxInflight。
我认为我们必须弄清楚发布卡住的原因或取消的方法。任何人都可以帮助解决这个问题吗?这是我当前的代码。
this.mqttClient = new MqttClient(
MqttConfiguration.END_POINT,
MqttConfiguration.CLIENT_ID
);
this.mqttClient.setCallback(this);
this.mqttClient.setTimeToWait(20000);
MqttConnectOptions options = new MqttConnectOptions();
options.setAutomaticReconnect(true);
options.setCleanSession(false);
options.setMaxInflight(1000);
this.mqttClient.connect(options);
return this.mqttClient.isConnected();
public boolean publish(
String topic,
GatewayCommandRequest command
) {
if (StringUtils.isEmpty(topic) || command == null || !this.isConnected()) return false;
try {
var commandStr = objectMapper.writeValueAsString(command);
MqttMessage msg = new MqttMessage(commandStr.getBytes(StandardCharsets.UTF_8));
msg.setQos(0);
this.mqttClient.publish(
topic,
msg
);
return true;
} catch (JsonProcessingException | MqttException e) {
JarvisLogger.logError(
ExceptionTag.MQTT_EXCEPTION,
"Publish Failed: " + topic,
e
);
}
return false;
}