[英]How to avoid MySQL connection timeout errors with EclipseLink?
如果沒有任何反應,MySQL會在一段時間后關閉連接( 默認情況下為8小時 )。 時間可能受配置中wait_timeout變量的影響。
我有一個Eclipse RCP應用程序,我使用EclipseLink作為持久性框架,當客戶端超過超時時出現錯誤:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
No operations allowed after connection closed.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
...
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
...
com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException
...
org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor...
我試圖設置autoReconnect / autoReconnectForPools = true但這沒有幫助。
謝謝
編輯
在我的persistence.xml中,我設置了以下屬性:
<property
name="eclipselink.jdbc.read-connections.max"
value="10" />
<property
name="eclipselink.jdbc.cache-statements"
value="true" />
<property
name="eclipselink.jdbc.read-connections.shared"
value="true" />
其余配置在代碼中完成:
Map<Object, Object> map = ...
map.put(PersistenceUnitProperties.JDBC_URL,...);
map.put(PersistenceUnitProperties.JDBC_USER,...);
map.put(PersistenceUnitProperties.JDBC_PASSWORD, ...);
map.put(PersistenceUnitProperties.JDBC_DRIVER, ...);
map.put(PersistenceUnitProperties.CLASSLOADER, this.getClass()
.getClassLoader());
map.put(PersistenceUnitProperties.TARGET_DATABASE, "MySQL");
entityManagerFactory = new PersistenceProvider()
.createEntityManagerFactory("...", map);
最簡單的方法是生成一個每小時左右發送一些keepalive或簡單查詢的線程。 在這里,我們將留下一個標志,以便線程可以在程序退出,數據庫更改等時關閉。如果它需要更快地響應該類型的關閉,您可以在for循環和休眠時間中更改計數器。
boolean parentKilledMe = false;
while (!parentKilledMe){
//put query here
for (int x = 0; x < 360 && !parentKilledMe;x++){
try{
Thread.sleep(6000);
} catch (InterruptedException e) {
//your error handling here
}
}
}
EclipseLink應自動重新連接死連接。 EclipseLink將捕獲錯誤,測試連接以及是否重新連接並可能重試查詢(如果在事務之外)。
但這取決於您使用的連接池,您的persistence.xml是什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.