Communications link failure due to underlying exception異常処理

2694 ワード

最近の項目はHibernateでC 3 P 0の接続プールを使用し、データベースはMysqlです.開発テストに問題はありません.実行中に長い空き時間ごとに異常が発生します.
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のドキュメントを確認し、Connector/Jのドキュメントとオンラインの説明を確認したところ、このような異常の原因は次のとおりです.
Mysqlサーバのデフォルトの「wait_timeout」は8時間です.つまり、1つのconnectionが8時間以上空いていると、Mysqlは自動的に接続を切断します.これが問題で、C 3 P 0 poolsのconnectionsが8時間以上空いている場合、Mysqlはそれを切断しますが、C 3 P 0はそのconnectionが失効したことを知らないので、Clientがconnectionを要求している場合、C 3 P 0はその失効したConnectionをClientに提供し、上面の異常をもたらします.
解決策は3つあります.
wait_を追加timeoutの時間.
Connection poolsのconnectionのlifetimeを減らします.
接続poolsでの接続の有効性をテストします.
もちろん最善の方法は上記3つの方法を併用することであり、以下DBPPとC 3 P 0をそれぞれ説明し、wait_timeoutはデフォルトの8時間です
DBCPでは、以下の構成情報を追加します.
 
//set to 'SELECT 1'
validationQuery = "SELECT 1"
//set to 'true'
testWhileIdle = "true"
//some positive integer
timeBetweenEvictionRunsMillis = 3600000
//set to something smaller than 'wait_timeout'
minEvictableIdleTimeMillis = 18000000
//if you don't mind a hit for every getConnection(), set to "true"
testOnBorrow = "true"

 C 3 P 0は、以下の構成情報を追加する.
 
//  connnection       
testConnectionOnCheckin = true
//     table  
automaticTestTable=C3P0TestTable
//set to something much less than wait_timeout, prevents connections from going stale
idleConnectionTestPeriod = 18000
//set to something slightly less than wait_timeout, preventing 'stale' connections from being handed out
maxIdleTime = 25000
//if you can take the performance 'hit', set to "true"
testConnectionOnCheckout = true

 
 詳細については、C 3 P 0ドキュメント、Connector/Jドキュメント、DBPPドキュメントを参照してください.