首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

MySQL 5.5+ 常見連線中斷原因與解決:wait_timeout 與連線池配置

     編輯:MySQL 綜合教學

現象

網站運行約 8 小時後無法連線資料庫,錯誤如「Connection reset」、「Communications link failure」。

根本原因

MySQL 5.5+ 預設 wait_timeout = 28800(8 小時)。閒置超過此時間,Server 主動斷開連線。應用端若持有失效連線(未驗證),下次使用即報錯。

解決方案一:調大 MySQL 端超時(治標)

[mysqld]
wait_timeout = 28800000
interactive_timeout = 28800000

重啟 MySQL 生效。將超時設為 8000 小時,實質上關閉閒置斷開。

解決方案二:應用端連線池驗證(治本,推薦)

以 Spring + DBCP/HikariCP 為例:

<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
    <property name="jdbcUrl" value="jdbc:mysql://host:3306/db?autoReconnect=true"/>
    <property name="username" value="user"/>
    <property name="password" value="pass"/>
    <!-- 關鍵:借用連線前執行輕量查詢驗證 -->
    <property name="connectionTestQuery" value="SELECT 1"/>
    <property name="testOnBorrow" value="true"/>
    <!-- 或定期驗證閒置連線 -->
    <property name="idleTimeout" value="300000"/>        
    <property name="maxLifetime" value="1800000"/>      
</bean>

原理: 連線池在借出連線前執行 SELECT 1,若連線已被 Server 斷開,驗證失敗則自動丟棄並建立新連線。

其他常見參數

參數建議值說明
wait_timeout28800 (8h)非互動式連線閒置超時
interactive_timeout28800互動式客戶端閒置超時
max_connections1000+最大連線數,配合連線池上限
net_read_timeout30讀取超時秒數
net_write_timeout60寫入超時秒數

最佳實踐總結

  1. MySQL 端保持預設或適度調大 wait_timeout
  2. 應用端**必須**啟用連線驗證(testOnBorrow / connectionTestQuery)
  3. 連線池 maxLifetime 設定 **小於** MySQL wait_timeout,確保連線在 Server 斷開前被主動回收重建
  4. 監控連線池指標:活躍/閒置/等待/創建失敗數
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved