MySQL異常【數據庫斷開鏈接】:Communications link failure

一.異常信息以及解決辦法

      
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:Communications link failure 
org.springframework.transaction.CannotCreateTransactionException: 
    Could not open JDBC Connection for transaction; 
    nested exception iscom.mysql.jdbc.exceptions.jdbc4.CommunicationsException: 
    Communications link failure
The last packet successfully received from the server was 6,388 milliseconds ago.  
The last packet sent successfully to the server was 1,504 milliseconds ago.
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:240)

異常分析:程序與MySQL通信失敗了,即鏈接失敗了。java

       此爲程序打開數據庫鏈接後,等到作數據庫操做時,發現鏈接被MySQL關閉掉了。而在MySQL這一層,MySQL5配置上默認將鏈接的等待時間(wait_timeout)缺省爲8小時。鏈接超過8小時,會致使mysql認爲這個鏈接超時無效,而後進行關閉。mysql

mysql﹥ 
mysql﹥ show global variables like 'wait_timeout'; 
+---------------+---------+ 
| Variable_name | Value | 
+---------------+---------+ 
| wait_timeout | 28800 | 
+---------------+---------+ 
1 row in set (0.00 sec) 
28800 seconds,也就是8小時。


解決辦法(嘗試方案順序可爲:(1)(3)(2)):
(1)在jdbc鏈接url的配置中,你能夠附上「autoReconnect=true」,但這僅對mysql5之前的版本起做用。

(2)既然問題是由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 

(3)咱們能夠將數據庫鏈接池的 validateQuery、testOnBorrow(testOnReturn)打開,這樣在 每次從鏈接池中取出且準備使用以前(或者使用完且在放入鏈接池以前)先測試下當前使用是否好用,若是很差用,系統就會自動destory掉。
或者testWhileIdle項是設置是否讓後臺線程定時檢查鏈接池中鏈接的可用性。linux


二.根本解決辦法:代碼優化



相似問題:java.net.SocketException四大異常解決方案spring

相關文章
相關標籤/搜索