首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

SpringMVC + MyBatis 數據庫連接失敗:Communications link failure 完整排查指南

     編輯:程式設計綜合問答

異常堆疊核心信息

org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction
nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory
(Communications link failure
The last packet successfully received from the server was 1,448,137,121,061 milliseconds ago.
The last packet sent successfully to the server was 0 milliseconds ago.)
Caused by: java.net.ConnectException: Connection refused: connect

根因分析

異常鏈清晰指向:應用無法建立到 MySQL 數據庫的 TCP 連接。Connection refused 表示目標端口無監聽進程或被防火牆攔截。

系統化排查步驟

  1. 驗證 MySQL 服務狀態
    # Linux
    systemctl status mysqld
    # 或
    service mysql status
    
    # Windows
    sc query mysql
  2. 確認端口監聽
    netstat -an | grep 3306
    ss -lntp | grep 3306
    若無輸出,檢查 my.cnf 中 port=3306 及 bind-address 設置。
  3. 網絡連通性測試
    telnet <db_host> 3306
    nc -zv <db_host> 3306
    若失敗,檢查安全組、防火牆、iptables 規則。
  4. 排除端口衝突
    lsof -i :3306
    確認無其他進程佔用 3306 端口。
  5. 檢查連接池配置
    • DBCP maxActive/maxTotal 是否過小導致連接耗盡
    • 驗證 validationQuery 設置(建議 SELECT 1)
    • 啟用 testOnBorrow 避免無效連接
  6. MySQL 服務端配置
    • max_connections 是否過小
    • wait_timeout/interactive_timeout 導致長連接被斷開
    • 錯誤日誌 /var/log/mysqld.log 查找異常

常見解決方案

  • 防火牆放行:firewall-cmd --add-port=3306/tcp --permanent
  • 調整連接池參數:適當增大 maxTotal、設置 minEvictableIdleTimeMillis
  • 使用連接字符串參數:autoReconnect=true&failOverReadOnly=false
  • 檢查 bind-address:生產環境建議綁定具體 IP 而非 127.0.0.1

最佳實踐建議

生產環境建議遷移至 HikariCP 連接池,並配置健康檢查機制;監控連接池指標(active/idle/usage),設置告警閾值。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved