【问题标题】:How to avoid MySQL connection timeout errors with EclipseLink?如何使用 EclipseLink 避免 MySQL 连接超时错误?
【发布时间】:2012-01-11 11:51:51
【问题描述】:

如果没有任何反应,MySQL 会在一段时间后关闭连接 (8 hours by default)。时间会受配置中的 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);

【问题讨论】:

    标签: java mysql jpa eclipselink connection-timeout


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢您的回答。我将我的配置添加到问题中。我没有找到如何在persistence.xml中配置它的解决方案。
    • 您使用的是什么版本的 EclipseLink?您能否包含完整的异常堆栈,并在获得时进行解释。如果你处理错误并重试,你会再次收到错误吗?
    • 同时删除“eclipselink.jdbc.read-connections.max”和“eclipselink.jdbc.read-connections.shared”设置,不推荐这些。使用“eclipselink.connection-pool.default.max”设置最大值(默认为 32),除非您使用的是旧版本。
    • 我使用的是 EclipseLink 2.2.0。现在升级到 2.3.1。我也按照你说的改变了参数设置。在此之后,我无法再重现该错误。非常感谢詹姆斯的帮助。
    【解决方案2】:

    执行此操作的最简单方法是生成一个线程,该线程每隔一小时左右发送某种 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
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      • 2020-07-31
      • 2012-07-27
      • 2021-02-05
      • 1970-01-01
      • 2012-11-01
      • 2010-09-24
      相关资源
      最近更新 更多