網站運行約 8 小時後無法連線資料庫,錯誤如「Connection reset」、「Communications link failure」。
MySQL 5.5+ 預設 wait_timeout = 28800(8 小時)。閒置超過此時間,Server 主動斷開連線。應用端若持有失效連線(未驗證),下次使用即報錯。
[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_timeout | 28800 (8h) | 非互動式連線閒置超時 |
| interactive_timeout | 28800 | 互動式客戶端閒置超時 |
| max_connections | 1000+ | 最大連線數,配合連線池上限 |
| net_read_timeout | 30 | 讀取超時秒數 |
| net_write_timeout | 60 | 寫入超時秒數 |
wait_timeouttestOnBorrow / connectionTestQuery)maxLifetime 設定 **小於** MySQL wait_timeout,確保連線在 Server 斷開前被主動回收重建