mysql 連接池連接超時的問題(The last packet sent successfully to the server was 776,652 milliseconds ago)

以下內容爲轉載http://www.blogjava.net/ivanwan/archive/2012/11/06/390893.html

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超時設置的問題
如果連接閒置8小時 (8小時內沒有進行數據庫操作), mysql就會自動斷開連接, 要重啓tomcat.

解決辦法:

一種. 如果不用hibernate的話, 則在 connection url中加參數: autoReconnect=true

jdbc.url=jdbc:mysql://ipaddress:3306/database?autoReconnect=true&autoReconnectForPools=true


二種。用hibernate的話, 加如下屬性:
<property name="connection.autoReconnect">true</property>
<property name="connection.autoReconnectForPools">true</property>
<property name="connection.is-connection-validation-required">true</property>


三。要是還用c3p0連接池:
<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數據庫,程序運行較長時間後就會報以下錯誤:

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。

其中錯誤還會提示你修改wait_timeout或是使用Connector/J的autoReconnect屬性避免該錯誤。

後來查了一些資料,才發現遇到這個問題的人還真不少,大部分都是使用連接池方式時纔會出現這個問題,短連接應該很難出現這個問題。這個問題的原因:

MySQL服務器默認的“wait_timeout”是28800秒即8小時,意味着如果一個連接的空閒時間超過8個小時,MySQL將自動斷開該連接,而連接池卻認爲該連接還是有效的(因爲並未校驗連接的有效性),當應用申請使用該連接時,就會導致上面的報錯。

1.按照錯誤的提示,可以在JDBC URL中使用autoReconnect屬性,實際測試時使用了autoReconnect=true& failOverReadOnly=false,不過並未起作用,使用的是5.1版本,可能真像網上所說的只對4之前的版本有效。

2.沒辦法,只能修改MySQL的參數了,wait_timeout最大爲31536000即1年,在my.cnf中加入:

[mysqld]

wait_timeout=31536000

interactive_timeout=31536000

重啓生效,需要同時修改這兩個參數

以上爲轉載,下面是自己有遇到的問題:

我還遇到過因爲語句執行太久也會出現The last packet successfully received from the server was *** millisecond ago.The last packet successfully sent to the server was *** millisecond ago。

我的語句是select last_insert_id() from weibo 用來取剛剛插入的id,由於線上表weibo太大,這句執行非常久,測試環境中沒測試出來,後來我纔想到不用from weibo表。select last_insert_id()是session級別的,自己會保證上條插入的id,我把語句改成select last_insert_id()就可以了。

發佈了44 篇原創文章 · 獲贊 23 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章