天天看點

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure解決

介紹

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 5,030 milliseconds ago.  The last packet sent successfully to the server was 28 milliseconds ago.


 

MySQL第二天早上第一次連接配接逾時報錯,解決方法
最近碰到一個mysql5資料庫的問題。就是一個标準的servlet/tomcat網絡應用,背景使用mysql資料庫。問題是待機一晚上後,第二天早上第一次登入總是失敗。察看日志發現如下錯誤:

“com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet successfully received from the server was 5,030 milliseconds ago.  The last packet sent successfully to the server was 28 milliseconds 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;來設定      

參考

本文為原創,如果您目前通路的域名不是surenpi.com,請通路“​​素人派​​”。