Pārlūkot izejas kodu

优化tdengine消费MQ设备数据消息程序逻辑,调整插入数据到数据库异常后的连接资源正常被释放

james 3 nedēļas atpakaļ
vecāks
revīzija
f77b591e7b

+ 26 - 3
data-tsdb-proxy/data-tsdb-proxy-biz/src/main/java/com/usky/demo/service/rocketmq/tdengine/tdengine.java

@@ -22,9 +22,11 @@ public class tdengine implements MqttStrategy {
 
     @Override
     public String disposeMessage(MQDataVO mqBaseVO) {
+        Connection conn = null;
+        Statement stmt = null;
         try {
-            Connection conn = dataSource.getConnection();
-            Statement stmt = conn.createStatement();
+            conn = dataSource.getConnection();
+            stmt = conn.createStatement();
 
             Map<String, String> tags = new HashMap<>();
             Map<String, Object> fields = new HashMap<>();
@@ -69,8 +71,29 @@ public class tdengine implements MqttStrategy {
             stmt.close();
             conn.close();
 
-        } catch (Exception e) {
+        }  catch (SQLException e) {
+            // 处理异常
+            System.err.println("SQL执行错误: " + e.getMessage());
             e.printStackTrace();
+
+        } finally {
+            // 必须在finally中关闭资源,确保无论是否发生异常都能释放
+            // 先关闭Statement,再关闭Connection
+            if (stmt != null) {
+                try {
+                    stmt.close();
+                } catch (SQLException e) {
+                    System.err.println("关闭Statement失败: " + e.getMessage());
+                }
+            }
+            if (conn != null) {
+                try {
+                    // 归还连接到连接池
+                    conn.close();
+                } catch (SQLException e) {
+                    System.err.println("关闭Connection失败: " + e.getMessage());
+                }
+            }
         }
         return "";
     }