From 0639f7feede9614a98f64450792cc83f58f80a84 Mon Sep 17 00:00:00 2001
From: liurunyu <lry9898@163.com>
Date: 星期三, 14 五月 2025 17:00:54 +0800
Subject: [PATCH] 与测控一体阀兼容
---
pipIrr-platform/pipIrr-web/pipIrr-web-app/src/main/java/com/dy/pipIrrApp/workOrder/mqtt/MqttClientConnectorPool.java | 87 +++++++++++++++++++++++++++++++++++++++++++
1 files changed, 87 insertions(+), 0 deletions(-)
diff --git a/pipIrr-platform/pipIrr-web/pipIrr-web-app/src/main/java/com/dy/pipIrrApp/workOrder/mqtt/MqttClientConnectorPool.java b/pipIrr-platform/pipIrr-web/pipIrr-web-app/src/main/java/com/dy/pipIrrApp/workOrder/mqtt/MqttClientConnectorPool.java
new file mode 100644
index 0000000..91a47e2
--- /dev/null
+++ b/pipIrr-platform/pipIrr-web/pipIrr-web-app/src/main/java/com/dy/pipIrrApp/workOrder/mqtt/MqttClientConnectorPool.java
@@ -0,0 +1,87 @@
+package com.dy.pipIrrApp.workOrder.mqtt;
+
+import lombok.extern.slf4j.Slf4j;
+import org.eclipse.paho.client.mqttv3.MqttClient;
+import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
+import org.eclipse.paho.client.mqttv3.MqttException;
+import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
+
+/**
+ * @author ZhuBaoMin
+ * @date 2024-11-16 11:27
+ * @LastEditTime 2024-11-16 11:27
+ * @Description MQTT瀹㈡埛绔繛鎺ユ睜锛屽澶栨彁渚涗竴涓垵濮嬪寲鐨凪QTT瀹㈡埛绔�
+ */
+
+@Slf4j
+public class MqttClientConnectorPool {
+ public static MqttClient mqttClient;
+
+ /**
+ * 杩炴帴MQTT瀹㈡埛绔�
+ * @return 鑾峰彇MQTT杩為槦瀵硅薄
+ */
+ public static MqttClient connectMQTT(String broker, String username, String password) {
+ if (mqttClient != null){
+ log.info("宸插瓨鍦紒");
+ return mqttClient;
+ }
+
+ try {
+ String clientId = System.currentTimeMillis() + "";
+
+ //鍒涘缓MQTT瀹㈡埛绔紙鎸囧畾broker銆佸鎴风id銆佹秷鎭寔涔呯瓥鐣ワ級
+ mqttClient = new MqttClient(broker, clientId, new MemoryPersistence());
+
+ //鍒涘缓杩炴帴鍙傛暟閰嶇疆
+ MqttConnectOptions options = new MqttConnectOptions();
+ options.setUserName(username);
+ options.setPassword(password.toCharArray());
+ //鏄惁娓呴櫎浼氳瘽
+ options.setCleanSession(true);
+ //杩炴帴瓒呮椂鏃堕棿
+ options.setKeepAliveInterval(20);
+ //鏄惁鑷姩閲嶈繛
+ options.setAutomaticReconnect(true);
+ mqttClient.connect(options);
+ log.info("MqttClient 鏈嶅姟鍚姩broker鍒濆鍖栵紒");
+ } catch (MqttException e){
+ log.error("MqttClient connect Error:{}", e.getMessage());
+ e.printStackTrace();
+ }
+ return mqttClient;
+ }
+
+ /**
+ * 鍏抽棴MQTT瀹㈡埛绔�
+ * @param client client
+ */
+ public static void closeClient(MqttClient client){
+ try {
+ // 鏂紑杩炴帴
+ client.disconnect();
+ // 鍏抽棴瀹㈡埛绔�
+ client.close();
+ } catch (MqttException e){
+ log.error("MqttClient disconnect or close Error锛歿}", e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * 鍏抽棴MQTT瀹㈡埛绔�
+ */
+ public static void closeStaticClient(){
+ try {
+ if (mqttClient != null){
+ // 鏂紑杩炴帴
+ mqttClient.disconnect();
+ // 鍏抽棴瀹㈡埛绔�
+ mqttClient.close();
+ }
+ } catch (MqttException e){
+ log.error("MqttClient disconnect or close Error锛歿}", e.getMessage());
+ e.printStackTrace();
+ }
+ }
+}
\ No newline at end of file
--
Gitblit v1.8.0