mysql - 在 MySQL、Grails 2 应用程序较长时间不活动期间保持池连接处于事件状态(或超时并获得新连接)的正确方法

标签 mysql grails connection-pooling connector-j

我有一个 grails 应用程序,它有一系列的高事件,但通常会持续几个小时甚至整晚不活动。我注意到早上的第一批用户会遇到以下类型的异常,我相信这是由于池中的连接过时并且 MYSql 数据库关闭了它们。

我在谷歌搜索中发现了相互矛盾的信息,即使用 Connector/J 连接属性“autoReconnect=true”是否是一个好主意(以及即使连接随后恢复,客户端是否仍会出现异常),或者是否设置将定期驱逐或刷新空闲连接、借用测试等的其他属性。Grails 在下面使用 DBCP。我目前有一个简单的配置,如下所示,我正在寻找有关如何最好地确保在长时间不活动后从池中抓取的任何连接有效且未关闭的答案。

dataSource {
        pooled = true
        dbCreate = "update"
        url = "jdbc:mysql://my.ip.address:3306/databasename"
        driverClassName = "com.mysql.jdbc.Driver"
        dialect = org.hibernate.dialect.MySQL5InnoDBDialect
        username = "****"
        password = "****"
        properties {
          //what should I add here?
          }
    }

异常(exception)

    2012-06-20 08:40:55,150 [http-bio-8443-exec-1] ERROR transaction.JDBCTransaction  - JDBC begin failed
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 64,129,968 milliseconds ago.  The last packet sent successfully to the server was 64,129,968 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
    at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3851)
    ...... Lots more .......
Caused by: java.sql.SQLException: Already closed.
    at org.apache.commons.dbcp.PoolableConnection.close(PoolableConnection.java:114)

最佳答案

最简单的方法是配置连接池以指定要运行的查询以在将连接传递给应用程序之前对其进行测试:

validationQuery="select 1 as dbcp_connection_test"
testOnBorrow=true

同样的“连接验证”查询可以在其他事件上运行。我不确定这些的默认值:

testOnReturn=true
testWhileIdle=true

还有一些配置设置可以限制池中空闲连接的“年龄”,如果空闲连接在服务器端被关闭,这可能很有用。

minEvictableIdleTimeMillis
timeBetweenEvictionRunsMillis

http://commons.apache.org/dbcp/configuration.html

关于mysql - 在 MySQL、Grails 2 应用程序较长时间不活动期间保持池连接处于事件状态(或超时并获得新连接)的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11125962/

相关文章:

php - 无法编辑数据库中的数据并且无法获取带有 ID 的名称?

Grails域类 transient 集合属性 setter 问题

grails - Grails Config:包括另一个配置文件

grails - grails复合ID无效

mysql - Sidekiq 在 AWS RDS 上返回 "ActiveRecord::ConnectionTimeoutError: could not obtain a database connection within 5.000 seconds (waited 5.000 seconds)"

asp.net-web-api2 - 最大池大小忽略使用 Azure SQL 和 Azure AppServices

javascript - 根据下拉框值统计MySql数据

php - "mysqli select"准备语句中的 php 函数出错

javascript - 使用Node.JS查询MySQL并在网页中显示结果

java.lang.IllegalStateException : Connection pool shut down exception