萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

MySQL 連線超時斷開異常徹底解決:原理、配置與連線池最佳實踐

異常現象

The last packet successfully received from the server was 43200 milliseconds ago.
... longer than the server configured value of 'wait_timeout'.
Connection.close() has already been called. Invalid operation in this state.

根本原因

MySQL wait_timeout(預設 28800 秒 = 8 小時)控制閒置連線最大存活時間。連線池借出的連線若閒置超過此值,Server 主動斷開;應用端再次使用時未檢測連線有效性,拋出異常。

解決方案對比

方案優點缺點推薦度
增大 wait_timeout(如 1 年)簡單治標不治本,資源浪費,仍有斷開風險★
連線池借用前測試治本,自動重連,資源可控微小效能開銷★★★★★
定期心跳/驗證查詢主動保持連線存活需額外排程,增加複雜度★★★
JDBC url 加 autoReconnect=true零代碼變更官方不推薦,可能掩蓋問題,事務安全性差★★

主流連線池配置範例

HikariCP(Spring Boot 2.x+ 預設)

spring.datasource.hikari.connection-test-query=SELECT 1
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.idle-timeout=300000        # 5 分鐘
spring.datasource.hikari.max-lifetime=1800000       # 30 分鐘
spring.datasource.hikari.connection-timeout=30000   # 30 秒獲取超時

Druid

spring.datasource.druid.validation-query=SELECT 1
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.test-on-return=false
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000

C3P0(Hibernate 原生)

hibernate.c3p0.testConnectionOnCheckout=true
hibernate.c3p0.preferredTestQuery=SELECT 1
hibernate.c3p0.idle_test_period=300
hibernate.c3p0.maxIdleTime=1800

驗證與監控

  • 啟用慢查詢日誌觀察 SELECT 1 執行頻率。
  • 監控連線池指標:ActiveConnections, IdleConnections, PendingThreads。
  • 壓測驗證:模擬閒置超過 wait_timeout 後繼續請求,確認無異常。
copyright © 萬盛學電腦網 all rights reserved