http://zeusami.iteye.com/blog/1112827
java
MySQL次日早上第一次鏈接超時報錯,解決方法com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure Last packet sent to the server was 0 ms ago
最近碰到一個mysql5數據庫的問題。就是一個標準的servlet/tomcat網絡應用,後臺使用mysql數據庫。問題是待機一夜後,次日早上第一次登陸老是失敗。察看日誌發現以下錯誤:
「com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Last packet sent to the server was 0 ms ago.」
通過一番調研,發現不少人都碰到過相似問題,但網上使人滿意的回答並很少。mysql網站上的提問也不少,但並無正確答案;百度知道上卻是有一個近似正確的回答。現將本人的解決辦法總結一下:
上述問題是由mysql5數據庫的配置引發的。mysql5將其鏈接的等待時間(wait_timeout)缺省爲8小時。在其客戶程序中能夠這樣來查看其值:
mysql﹥
mysql﹥ show global variables like 'wait_timeout';
+---------------+---------+
| Variable_name | Value |
+---------------+---------+
| wait_timeout | 28800 |
+---------------+---------+
1 row in set (0.00 sec)
28800 seconds,也就是8小時。
若是在wait_timeout秒期間內,數據庫鏈接(java.sql.Connection)一直處於等待狀態,mysql5就將該鏈接關閉。這時,你的Java應用的鏈接池仍然合法地持有該鏈接的引用。當用該鏈接來進行數據庫操做時,就碰到上述錯誤。這解釋了爲何個人程序次日不能登陸 的問題。
你可能會想到在tomcat的數據源配置中有沒有辦法解決?的確,在jdbc鏈接url的配置中,你能夠附上「autoReconnect=true」,但這僅對mysql5之前的版本起做用。增長「validation query」彷佛也無濟於事。
本人以爲最簡單的辦法,就是對症下藥:既然問題是由mysql5的全局變量wait_timeout的缺省值過小引發的,咱們將其改大就行了。
查看mysql5的手冊,發現對wait_timeout的最大值分別是24天/365天(windows/linux)。以windows爲 例,假設咱們要將其設爲21天,咱們只要修改mysql5的配置文件「my.ini」(mysql5 installation dir),增長一行:wait_timeout=1814400
須要從新啓動mysql5。
linux系統配置文件:/etc/my.cnf
測試顯示問題解決了。
也能夠直接設置
mysql修改wait_timeout
mysql mysql> show global variables like 'wait_timeout';
其默認值爲8小時
mysql的一個connection空閒時間超過8小時,mysql會自動斷開該鏈接。
1.修改配置
vi /etc/my.cnf
[mysqld] wait_timeout=10
# /etc/init.d/mysql restart
2.直接用sql命令行修改 mysql> set global wait_timeout=604800;
除了wait_timeout,還有一個'interactive_timeout'
一樣能夠執行SHOW GLOBAL VARIABLES LIKE 'interactive_timeout'來查詢
執行set global interactive_timeout=604800;來設置 mysql