|
|
@@ -52,7 +52,7 @@ public class MqttClientUtil implements ApplicationContextAware {
|
|
|
try {
|
|
|
mqttClientFactory = applicationContext.getBean(MqttPahoClientFactory.class);
|
|
|
} catch (Exception e) {
|
|
|
-
|
|
|
+ // 忽略异常,如果获取不到工厂则无法进行MQTT操作
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -96,14 +96,14 @@ public class MqttClientUtil implements ApplicationContextAware {
|
|
|
*/
|
|
|
public void publish(String hospitalCode, String topic, Object payload, int qos, boolean retained) {
|
|
|
try {
|
|
|
- // 创建消息实体
|
|
|
- MqttMessage message = new MqttMessage(topic, JSONUtil.toJsonStr( payload));
|
|
|
- message.setClientId(CLIENT_ID);
|
|
|
-
|
|
|
if (mqttClientFactory == null) {
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
+ // 创建消息实体
|
|
|
+ MqttMessage message = new MqttMessage(topic, JSONUtil.toJsonStr(payload));
|
|
|
+ message.setClientId(CLIENT_ID);
|
|
|
+
|
|
|
MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(CLIENT_ID, mqttClientFactory);
|
|
|
messageHandler.setDefaultTopic("hospitalInfo/"+hospitalCode);
|
|
|
messageHandler.setDefaultQos(qos);
|
|
|
@@ -125,14 +125,14 @@ public class MqttClientUtil implements ApplicationContextAware {
|
|
|
* @param topic 主题
|
|
|
* @param messageHandler 消息处理器
|
|
|
*/
|
|
|
- public void subscribe( String topic, MessageHandler messageHandler) {
|
|
|
+ public void subscribe(String topic, MessageHandler messageHandler) {
|
|
|
try {
|
|
|
if (mqttClientFactory == null) {
|
|
|
return;
|
|
|
}
|
|
|
// 如果已经订阅了该主题,则先取消订阅
|
|
|
if (subscribers.containsKey(topic)) {
|
|
|
- unsubscribe( topic);
|
|
|
+ unsubscribe(topic);
|
|
|
}
|
|
|
|
|
|
MqttPahoMessageDrivenChannelAdapter adapter =
|
|
|
@@ -173,12 +173,15 @@ public class MqttClientUtil implements ApplicationContextAware {
|
|
|
* 取消订阅
|
|
|
* @param topic 主题
|
|
|
*/
|
|
|
- public void unsubscribe( String topic) {
|
|
|
- String key = topic;
|
|
|
- MqttPahoMessageDrivenChannelAdapter adapter = subscribers.get(key);
|
|
|
+ public void unsubscribe(String topic) {
|
|
|
+ MqttPahoMessageDrivenChannelAdapter adapter = subscribers.get(topic);
|
|
|
if (adapter != null) {
|
|
|
- adapter.stop();
|
|
|
- subscribers.remove(key);
|
|
|
+ try {
|
|
|
+ adapter.stop();
|
|
|
+ } catch (Exception e) {
|
|
|
+ // 忽略停止异常
|
|
|
+ }
|
|
|
+ subscribers.remove(topic);
|
|
|
}
|
|
|
}
|
|
|
|