1. 程式人生 > >Hibernate連線資料庫超時設定

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的話, 加如下屬性:

<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>

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

另外的解決辦法:

解決hibernate+mysql出現的隔天連線超時問題

出現錯誤: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 ago

問題出現原因
mysql預設為8小時後自動消除空閒連線,而hibernate預設空連線超時時間大於這個數。

解決方法
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>

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