標籤:
一.異常資訊以及解決辦法
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 failureThe 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通訊失敗了,即串連失敗了。
此為程式開啟資料庫連接後,等到做資料庫操作時,發現串連被MySQL關閉掉了。而在MySQL這一層,MySQL5配置上預設將串連的等待時間(wait_timeout)預設為8小時。串連超過8小時,會導致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)在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項是設定是否讓後台線程定時檢查串連池中串連的可用性。
MySQL異常【資料庫中斷連線】:Communications link failure