连接池在 Tomcat 7 中静默过期,但 autoReconnect=true 没有修复它

Connection pool expires silently in Tomcat 7 but autoReconnect=true doesn't fix it

几周来我一直收到这些异常,但没有解决方案...

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 179,695,604 milliseconds ago.

The last packet sent successfully to the server was 179,695,604 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

所以我更改了我的应用程序的 Context.xml 以在 Tomcat 7 中为我的数据库设置 autoReconnect=true 标记以进行连接池。我什至将 wait_timeout 设置为上下文文件中的无穷大。

我错过了什么?这是个常见的问题吗?网上似乎有少量信息,但是当我按照这些指南进行操作时,在一段时间不活动后第二天又发生了同样的事情。

我使用服务器越多,这种情况就越少。我认为这是池连接到期,但如果 wait_timeout 失败,我该如何阻止它们到期?关于如何诊断问题或配置文件的任何想法?

MySQL Connector/J documentationautoReconnect:

If enabled the driver will throw an exception for a queries issued on a stale or dead connection, which belong to the current transaction, but will attempt reconnect before the next query issued on the connection in a new transaction.

这意味着您仍然会遇到异常。

JDBI 等连接器通过在空闲时添加可选的测试查询、从池中借用和 return 到池中来解决这个问题。也许您可以在自己的 JDBC 连接包装器中添加一些东西来做同样的事情。或者,按照 autoReconnect 的文档并正确捕获由 dead/stale 个连接引起的 SQLExceptions。

关于 this answer 使用 DBCP 和 c3p0

还有更多有用的参考资料

我遇到了类似的问题,autoReconnect=true 引发了 CommunicationsException 异常,但随后创建了到 mysql 的新连接。所以下一个请求会成功。此行为将继续发生,空闲时间后的第一个请求将失败。 为了补充 Alex 已经回答的内容,我将以下参数添加到我的 JDBC 连接字符串中,我再也看不到错误了。

 testOnBorrow="true" validationQuery="SELECT 1" validationInterval="60000"

testOnBorrow 的描述足以说明这一点。好处是我不必对我的代码进行任何更改。

参考资料: https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html http://www.tomcatexpert.com/blog/2010/04/01/configuring-jdbc-pool-high-concurrency