|
@@ -3,31 +3,24 @@ package cn.reghao.autodop.common.mqtt;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
import org.eclipse.paho.client.mqttv3.*;
|
|
import org.eclipse.paho.client.mqttv3.*;
|
|
|
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
|
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
|
|
-import org.springframework.stereotype.Component;
|
|
|
|
|
-
|
|
|
|
|
-import java.util.UUID;
|
|
|
|
|
|
|
|
|
|
/**
|
|
/**
|
|
|
* @author reghao
|
|
* @author reghao
|
|
|
* @date 2021-05-21 08:27:41
|
|
* @date 2021-05-21 08:27:41
|
|
|
*/
|
|
*/
|
|
|
@Slf4j
|
|
@Slf4j
|
|
|
-@Component
|
|
|
|
|
public class MqttSub implements AutoCloseable {
|
|
public class MqttSub implements AutoCloseable {
|
|
|
private MosquittoProperties properties;
|
|
private MosquittoProperties properties;
|
|
|
private MqttClient client;
|
|
private MqttClient client;
|
|
|
|
|
|
|
|
- public MqttSub(MosquittoProperties properties) throws MqttException {
|
|
|
|
|
|
|
+ public MqttSub(String clientId, MosquittoProperties properties) throws MqttException {
|
|
|
this.properties = properties;
|
|
this.properties = properties;
|
|
|
- this.client = new MqttClient(properties.getBroker(), UUID.randomUUID().toString(), new MemoryPersistence());
|
|
|
|
|
|
|
+ this.client = new MqttClient(properties.getBroker(), clientId, new MemoryPersistence());
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
private MqttConnectOptions connectOptions() {
|
|
private MqttConnectOptions connectOptions() {
|
|
|
MqttConnectOptions options = new MqttConnectOptions();
|
|
MqttConnectOptions options = new MqttConnectOptions();
|
|
|
- options.setCleanSession(true);
|
|
|
|
|
- options.setConnectionTimeout(10);
|
|
|
|
|
- options.setKeepAliveInterval(30);
|
|
|
|
|
- options.setAutomaticReconnect(true);
|
|
|
|
|
|
|
+ options.setCleanSession(false);
|
|
|
options.setUserName(properties.getUsername());
|
|
options.setUserName(properties.getUsername());
|
|
|
options.setPassword(properties.getPassword().toCharArray());
|
|
options.setPassword(properties.getPassword().toCharArray());
|
|
|
return options;
|
|
return options;
|
|
@@ -38,9 +31,19 @@ public class MqttSub implements AutoCloseable {
|
|
|
client.close();
|
|
client.close();
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 确保能订阅到离线消息的设置:
|
|
|
|
|
+ * - qos=1
|
|
|
|
|
+ * - clientId 确定,不能使用随机的 UUID
|
|
|
|
|
+ * - CleanSession=false
|
|
|
|
|
+ *
|
|
|
|
|
+ * @param
|
|
|
|
|
+ * @return
|
|
|
|
|
+ * @date 2021-06-16 下午8:39
|
|
|
|
|
+ */
|
|
|
public void sub(String topic, MqttCallback callback) throws MqttException {
|
|
public void sub(String topic, MqttCallback callback) throws MqttException {
|
|
|
client.connect(connectOptions());
|
|
client.connect(connectOptions());
|
|
|
- client.subscribe(topic);
|
|
|
|
|
client.setCallback(callback);
|
|
client.setCallback(callback);
|
|
|
|
|
+ client.subscribe(topic, 1);
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|