Hibernate鏈接數據庫超時設置

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.
解決辦法:
若是鏈接閒置8小時 (8小時內沒有進行數據庫操做), mysql就會自動斷開鏈接, 要重啓tomcat. 
不用hibernate的話, connection url加參數: autoReconnect=true 
用hibernate的話, 加以下屬性:java

<property name="connection.autoReconnect">true</property> 
<property name="connection.autoReconnectForPools">true</property> 
<property name="connection.is-connection-validation-required">true</property>mysql

要是還用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>web

或者最王道的解決辦法,那就是直接修改mysql的配置文件my.ini 在配置文件的最後增長wait_timeout=343232後面的數字是以秒計算。改個10年100年多方便的。sql

另外的解決辦法:數據庫

解決hibernate+mysql出現的隔天鏈接超時問題tomcat

出現錯誤:SQL Error: 0, SQLState: 08S01
Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
Java.NET.SocketException
MESSAGE: Software caused connection abort: socket write error
STACKTRACE:
java.Net.SocketException: Software caused connection abort: socket write error
** END NESTED EXCEPTION **
Last packet sent to the server was 0 ms agoapp

問題出現緣由
mysql默認爲8小時後自動消除空閒鏈接,而hibernate默認空鏈接超時時間大於這個數。socket

解決方法
1.找到mysql5.0目錄下的my.ini文件,在最底處(或任意位置)添加wait_timeout =60(60爲自定義值)
2.用c3p0代替hibernate的鏈接池。c3p0.9.1.jar可從hibernate開源項目的lib下面找到,將其拷貝到web-inf/lib下面。在hibernate.cfg.xml配置文件中添加如下信息:
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.validate">false</property>ide

其中hibernate.c3p0.timeout屬性指定多少秒後鏈接超時,鏈接池會自動對超時鏈接進行重查。ui

相關文章
相關標籤/搜索