最近的一個項目在Hibernate使用C3P0的連接池,數據庫為Mysql。開發測試沒有問題,在運行中每個一段長的空閑時間就出現異常:
- org.hibernate.exception.JDBCConnectionException: could not execute query
- at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
- at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
- .......
- Caused by: com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: No operations allowed after connection closed.Connection was implicitly closed due to underlying exception/error:
-
-
- ** BEGIN NESTED EXCEPTION **
-
- com.mysql.jdbc.CommunicationsException
- MESSAGE: Communications link failure due to underlying exception:
-
- ** BEGIN NESTED EXCEPTION **
-
- java.net.SocketException
- MESSAGE: Broken pipe
-
- STACKTRACE:
-
- java.net.SocketException: Broken pipe
- at java.net.SocketOutputStream.socketWrite0(Native Method)
- ......
- ** END NESTED EXCEPTION **
查看了Mysql的文檔,以及Connector/J的文檔以及在線說明發現,出現這種異常的原因是:
Mysql服務器默認的“wait_timeout”是8小時,也就是說一個connection空閑超過8個小時,Mysql將自動斷開該connection。這就是問題的所在,在C3P0 pools中的connections如果空閑超過8小時,Mysql將其斷開,而C3P0并不知道該connection已經失效,如果這時有Client請求connection,C3P0將該失效的Connection提供給Client,將會造成上面的異常。
解決的方法有3種:
- 增加wait_timeout的時間。
- 減少Connection pools中connection的lifetime。
- 測試Connection pools中connection的有效性。
當然最好的辦法是同時綜合使用上述3種方法,下面就DBCP和C3P0分別做一說明,假設wait_timeout為默認的8小時
DBCP增加以下配置信息:
validationQuery = "SELECT 1"
testWhileIdle = "true"
timeBetweenEvictionRunsMillis = 3600000
minEvictableIdleTimeMillis = 18000000
testOnBorrow = "true"
C3P0增加以下配置信息:
testConnectionOnCheckin = true
//自動測試的table名稱
automaticTestTable=C3P0TestTable
idleConnectionTestPeriod = 18000
maxIdleTime = 25000
testConnectionOnCheckout = true
在配置文件中要寫成 <property name="minPoolSize"><value>1</value></property> 格式
不能寫成 這樣<property name="properties">
<props>
<prop key="c3p0.initialPoolSize">1</prop>
</props>
</property>
c3p0不能完全識別!!