`

使用hibernate连接mysql自动中断的问题

阅读更多

数据库为mysql,客户端使用hibernate进行连接,结果长时间没有数据访问的话,重新访问数据库就会报错:

java 代码
  1. org.hibernate.exception.JDBCConnectionException: could not execute query    
  2. at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)    
  3. at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)    
  4. .......    
  5. Caused by: com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: No operations allowed after connection closed.Connection was implicitly closed due to underlying exception/error:    
  6.   
  7.   
  8. ** BEGIN NESTED EXCEPTION **    
  9.   
  10. com.mysql.jdbc.CommunicationsException    
  11. MESSAGE: Communications link failure due to underlying exception:    
  12.   
  13. ** BEGIN NESTED EXCEPTION **    
  14.   
  15. java.net.SocketException    
  16. MESSAGE: Broken pipe    
  17.   
  18. STACKTRACE:    
  19.   
  20. java.net.SocketException: Broken pipe    
  21. at java.net.SocketOutputStream.socketWrite0(Native Method)    
  22. ......    
  23. ** END NESTED EXCEPTION **    

查阅相关文档,造成报错的原因在于:Mysql服务器默认的“wait_timeout”是8小时,也就是说一个connection空闲超过8个小时,Mysql将自动断开该connection。

解决的方法有3种:

  1. 增加wait_timeout的时间。
  2. 减少Connection pools中connection的lifetime。
  3. 测试Connection pools中connection的有效性。

使用c3p0解决上面问题的配置如下:

   <!---->

java 代码
  1. <!---->  
  2.     "c3p0.min_size">10   
  3.     "c3p0.max_size">100   
  4.     "c3p0.timeout">10   
  5.     "c3p0.acquireRetryAttempts">30   
  6.   
  7.     "c3p0.acquireIncrement">5   
  8.   
  9.     <!---->
  10.     "c3p0.idleConnectionTestPeriod">300   
  11.   
  12.     "c3p0.initialPoolSize">20   
  13.     "c3p0.maxPoolSize">100   
  14.     <!---->
  15.     "c3p0.maxIdleTime">300   
  16.     "c3p0.maxStatements">50   
  17.     "c3p0.minPoolSize">10  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics