不要使用Paho库生成的消息的MQTT id - 因为它
相反,使用您自己的ID(甚至可能由您的数据库自动生成)并将其作为用户定义传递 上下文对象 什么时候 出版 :
Long databaseId = 42; ObjectMapper objectMapper = new ObjectMapper(); MqttMessage mqttMessage = new MqttMessage(); mqttMessage.setPayload(objectMapper.writeValueAsString(myObject).getBytes()); mqttMessage.setQos(1); this.client.publish("/myTopic", mqttMessage, databaseId, mPublishCallback);
稍后您可以在发布回调方法中检索id:
private final IMqttActionListener mPublishCallback = new IMqttActionListener() { @Override public void onSuccess(IMqttToken publishToken) { Long databaseId = (Long) publishToken.getUserContext(); } @Override public void onFailure(IMqttToken publishToken, Throwable ex) { Long databaseId = (Long) publishToken.getUserContext(); } };
另外,您使用的是同步客户端吗?我更喜欢使用 IMqttAsyncClient