关键字: hibernate, mysql, c3p0
数据库为mysql,客户端使用hibernate进行连接,结果长时间没有数据访问的话,重新访问数据库就会报错:
java 代码
- 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服务器默认的“wait_timeout”是8小时,也就是说一个connection空闲超过8个小时,Mysql将自动断开该connection。
解决的方法有3种:
- 增加wait_timeout的时间。
- 减少Connection pools中connection的lifetime。
- 测试Connection pools中connection的有效性。
使用c3p0解决上面问题的配置如下:
<!-- C3P0 Connection Pool-->
java 代码
- <!-- C3P0 Connection Pool-->
- "c3p0.min_size">10
- "c3p0.max_size">100
- "c3p0.timeout">10
- "c3p0.acquireRetryAttempts">30
-
- "c3p0.acquireIncrement">5
-
- <!--<span class="comment">//set to something much less than wait_timeout, prevents connections from going stale-->
- "c3p0.idleConnectionTestPeriod">300
-
- "c3p0.initialPoolSize">20
- "c3p0.maxPoolSize">100
- <!--<span class="comment">//set to something slightly less than wait_timeout, preventing 'stale' connections from being handed out -->
- "c3p0.maxIdleTime">300
- "c3p0.maxStatements">50
- "c3p0.minPoolSize">10
|