之前做了一個web項(xiàng)目的時候,好好的網(wǎng)站第二天總是會提示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è)置的問題。如 果連接閑置8小時 (8小時內(nèi)沒有進(jìn)行數(shù)據(jù)庫操作), mysql就會自動斷開連接
第一種解決方案是在 connection url中加參數(shù): autoReconnect=true
1 | jdbc.url=jdbc:mysql://ipaddress:3306/database?autoReconnect= true &autoReconnectForPools= true |
第二種如果使用hibernate的時候做如下配置1 | < property name = "connection.autoReconnect" >true</ property > |
2 | < property name = "connection.autoReconnectForPools" >true</ property > |
3 | < property name = "connection.is-connection-validation-required" >true</ property > |
如果使用了c3p0做如下配置1 | < property name = "hibernate.c3p0.acquire_increment" >1</ property > |
2 | < property name = "hibernate.c3p0.idle_test_period" >0</ property > |
3 | < property name = "hibernate.c3p0.timeout" >0</ property > |
4 | < property name = "hibernate.c3p0.validate" >true</ property > |
第三種方法如下:大部分都是使用連接池方式時才會出現(xiàn)這個問題,短連接應(yīng)該很難出現(xiàn)這個問題。這個問題的原因:
MySQL服務(wù)器默認(rèn)的“wait_timeout”是28800秒即8小時,意味著如果一個連接的空閑時間超過8個小時,MySQL將自動斷開該 連接,而連接池卻認(rèn)為該連接還是有效的(因?yàn)椴⑽葱r?yàn)連接的有效性),當(dāng)應(yīng)用申請使用該連接時,就會導(dǎo)致上面的報(bào)錯。
1.按照錯誤的提示,可以在JDBC URL中使用autoReconnect屬性,實(shí)際測試時使用了autoReconnect=true& failOverReadOnly=false,不過并未起作用,使用的是5.1版本,可能真像網(wǎng)上所說的只對4之前的版本有效。
2.沒辦法,只能修改MySQL的參數(shù)了,wait_timeout最大為31536000即1年,在my.cnf中加入:
3 | interactive_timeout=31536000 |
重啟生效,需要同時修改這兩個參數(shù)。
參考文檔: http://aayy520.blog.163.com/blog/static/23182260201102994534777/
總結(jié)一下,這種問題主要是使用了連接池沒有識別出過期的鏈接,解決方案就是數(shù)據(jù)庫連接加一個autoReconnect的參數(shù)。或者使用框架的一些參數(shù)來控制。