前言
本文主要給大家介紹的是關(guān)于JDBC實(shí)現(xiàn)Mysql自動(dòng)重連機(jī)制的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面來一起看看詳細(xì)的介紹:
日志:using the Connector/J connection property 'autoReconnect=true' to avoid this problem
1
|
com.mysql.jdbc.CommunicationsException: The last packet successfully received from the server was58129 seconds ago.The last packet sent successfully to the server was 58129 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. |
查了一下,原來是MySQL超時(shí)設(shè)置的問題
如果連接閑置8小時(shí) (8小時(shí)內(nèi)沒有進(jìn)行數(shù)據(jù)庫操作), mysql就會(huì)自動(dòng)斷開連接, 要重啟tomcat.
解決辦法:
第一種:如果不用hibernate的話, 則在 connection url中加參數(shù): autoReconnect=true
1
|
jdbc.url=jdbc:mysql: //ipaddress:3306/database?autoReconnect=true&autoReconnectForPools=true |
第二種:用hibernate的話, 加如下屬性:
1
2
3
|
<property name= "connection.autoReconnect" > true </property> <property name= "connection.autoReconnectForPools" > true </property> <property name= "connection.is-connection-validation-required" > true </property> |
第三種:要是還用c3p0連接池:
1
2
3
4
|
<property name= "hibernate.c3p0.acquire_increment" > 1 </property> <property name= "hibernate.c3p0.idle_test_period" > 0 </property> <property name= "hibernate.c3p0.timeout" > 0 </property> <property name= "hibernate.c3p0.validate" > true </property> |
第四種:最不好的解決方案
使用Connector/J連接MySQL數(shù)據(jù)庫,程序運(yùn)行較長時(shí)間后就會(huì)報(bào)以下錯(cuò)誤:
Communications link failure,The last packet successfully received from the server was *** millisecond ago.The last packet successfully sent to the server was *** millisecond ago。
其中錯(cuò)誤還會(huì)提示你修改wait_timeout或是使用Connector/J的autoReconnect屬性避免該錯(cuò)誤。
后來查了一些資料,才發(fā)現(xiàn)遇到這個(gè)問題的人還真不少,大部分都是使用連接池方式時(shí)才會(huì)出現(xiàn)這個(gè)問題,短連接應(yīng)該很難出現(xiàn)這個(gè)問題。
這個(gè)問題的原因:
MySQL服務(wù)器默認(rèn)的“wait_timeout”是28800秒即8小時(shí),意味著如果一個(gè)連接的空閑時(shí)間超過8個(gè)小時(shí),MySQL將自動(dòng)斷開該 連接,而連接池卻認(rèn)為該連接還是有效的(因?yàn)椴⑽葱r?yàn)連接的有效性),當(dāng)應(yīng)用申請(qǐng)使用該連接時(shí),就會(huì)導(dǎo)致上面的報(bào)錯(cuò)。
⑴.按照錯(cuò)誤的提示,可以在JDBC URL中使用autoReconnect屬性,實(shí)際測試時(shí)使用了autoReconnect=true& failOverReadOnly=false
,不過并未起作用,使用的是5.1版本,可能真像網(wǎng)上所說的只對(duì)4之前的版本有效。
⑵.沒辦法,只能修改MySQL的參數(shù)了,wait_timeout最大為31536000即1年,在my.cnf中加入:
1
2
3
4
5
|
[mysqld] wait_timeout=31536000 interactive_timeout=31536000 |
重啟生效,需要同時(shí)修改這兩個(gè)參數(shù)。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)服務(wù)器之家的支持。
原文鏈接:http://blog.csdn.net/dodott/article/details/54616333