MySQL 的 wait_timeout 連接超時除錯解決方案
MySQL 的 wait_timeout
參數決定了客戶端連接的最大閒置時間。如果時間超過,未執行任何操作的連接會被強制關閉,導致應用程序報錯或斷線。
什麼是 wait_timeout
?
wait_timeout
是 MySQL 的一個伺服器級參數,用於控制客戶端連接的閒置時間上限(以秒為單位)。當連接超過設定時間且未發送任何請求時,MySQL 將自動斷開該連接。
常見問題與徵兆
以下是由 wait_timeout
設定過低引發的常見問題:
- 應用程序頻繁報錯,例如“The last packet successfully received from the server was 43,399,376 milliseconds ago. The last packet sent successfully to the server was 43,399,376 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem. com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 43,399,376 milliseconds ago. The last packet sent successfully to the server was 43,399,376 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.”或是 “MySQL server has gone away”。
- Navicat 的查詢或操作中斷,必須重新連接。
- 資料庫連接性能降低,影響應用程式運行穩定性。
如何檢查 wait_timeout
值?
使用 Navicat 檢查 wait_timeout
值非常簡單:
- 打開 Navicat 並連接到 MySQL 資料庫。
- 在工具列選擇 查詢,進入 SQL 編輯器。
- 輸入以下查詢並執行:
SHOW VARIABLES LIKE 'wait_timeout';
- 檢視結果表,記錄當前的
wait_timeout
值。
如何調整 wait_timeout
值?
若當前的 wait_timeout
設定過低,可根據以下步驟進行調整:
1. 暫時修改 wait_timeout
可在 Navicat 中執行以下命令(F6)暫時更改 wait_timeout
值(直到 MySQL 重啟):
SET GLOBAL wait_timeout = 28800;
注意:將值設置為較高的秒數(如 28800,即 8 小時),以滿足應用程序需求。

圖3:在 Navicat 中修改全域參數
2. 永久修改 wait_timeout
若需永久更改,可修改 MySQL 的配置檔案 my.ini
或 my.cnf
(Windows 系統預設為 my.ini
)。
- 找到
my.ini
文件,一般位於 MySQL 的安裝目錄中。 - 用文字編輯器打開文件,找到
[mysqld]
區塊。 - 新增或修改以下參數:
wait_timeout=28800
- 保存文件後,重新啟動 MySQL 服務以使更改生效。
3. 減少不必要的閒置連接
除了調整 wait_timeout
,也可以優化應用程序的連接管理,例如:
- 實現連接池,減少每次查詢的連接開銷。
- 關閉不必要的持續連接,減少 MySQL 負載。
最佳實踐建議
以下是管理 wait_timeout
的一些最佳實踐建議:
- 根據應用需求,將
wait_timeout
設為合理的範圍(如 30 分鐘到 8 小時)。 - 定期檢查資料庫性能,確保調整參數後的穩定性。
- 搭配 Navicat 的日誌檢視功能,監控連接狀況和錯誤記錄。
結論
MySQL 的 wait_timeout
是影響連接穩定性的重要參數。透過 Navicat 檢查與調整此參數,並搭配應用程序的連接優化措施,可以有效避免頻繁斷線和超時問題。