問題描述:系統本來運行正常,但過一段時間,或待機一晚上後,第二天早上第一次登錄總是失敗。查看日誌或Tomcat控制檯輸出,發現如下錯誤信息:
Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was41968 seconds ago.The last packet sent successfully to the server was 41968 seconds ago, which 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.
解決方法來自:http://www.svn8.com/mysql/200906036013.html
http://i5tt.javaeye.com/blog/380324
經過一番調研,發現很多人都碰到過類似問題,但網上令人滿意的回答並不多。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就將該連接關閉。這時,你的JavaEE應用的連接池仍然合法地持有該連接的引用。當用該連接來進行數據庫操作時,就碰到上述錯誤。這解釋了爲什麼程序第二天不能登錄的問題。
你可能會想到在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)中的[mysqld]後面增加一行:wait_timeout=1814400
需要重新啓動mysql5。
linux系統配置文件:/etc/my.cnf
測試顯示問題解決了。