3

如果没有任何反应,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);
4

2 回答 2

2

最简单的方法是生成一个线程,每隔一小时左右发送某种保活或简单查询。在这里,我们会留下一个标志,以便线程可以在程序退出、数据库更改等时关闭。如果它需要更快地响应这种类型的关闭,您可以更改 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
        }
    }
}
于 2011-12-02T13:57:30.243 回答
2

EclipseLink 应该自动重新连接死连接。EclipseLink 将捕获错误,测试连接,如果死了重新连接并可能重试查询(如果在事务之外)。

但这取决于您使用的是什么连接池,您的persistence.xml 是什么。

于 2011-12-05T18:16:09.880 回答