MySql 超时 - 我应该在 Spring 应用程序中设置 autoReconnect=true 吗?
在我的网站一段时间不活动后(使用 Spring 2.5 和 MySql),我收到以下错误:
org.springframework.dao.RecoverableDataAccessException:最后一个成功发送到服务器的数据包是在 52,847,830 毫秒前。比服务器配置的“wait_timeout”值长。您应该考虑在应用程序中使用之前过期和/或测试连接有效性,增加客户端超时的服务器配置值,或使用 Connector/J 连接属性“autoReconnect=true”来避免此问题。
根据这个问题,以及链接错误,我不应该只设置 autoReconnect=true。这是否意味着我必须在执行的任何查询中捕获此异常,然后重试事务?该逻辑应该位于数据访问层还是模型层?有没有一种简单的方法来处理这个问题,而不是包装每个查询来捕获这个问题?
After periods of inactivity on my website (Using Spring 2.5 and MySql), I get the following error:
org.springframework.dao.RecoverableDataAccessException: The last packet sent successfully to the server was 52,847,830 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.
According to this question, and the linked bug, I shouldn't just set autoReconnect=true. Does this mean I have to catch this exception on any queries I do and then retry the transaction? Should that logic be in the data access layer, or the model layer? Is there an easy way to handle this instead of wrapping every single query to catch this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您改用连接池。它们提高了性能并可以处理低级细节,例如超时后重新连接等。
c3p0 是一个不错的选择,但还有其他的。 Spring 对此支持,虽然我不知道所有细节。 这里是
DataSource
的配置为了春天。I would suggest that you use a connection pool instead. They improve performance and can take care of the low-level details such as reconnect after timeout, etc.
A good one is c3p0, but there are others. Spring has support for that, though I don't know all the details. Here is the configuration of a
DataSource
for Spring.此异常可能有 2 个原因:
您没有正确关闭 JDBC 资源。所有
Connection
、Statement
和ResultSet
必须在finallytry
块的 code> 块。这与您是否使用连接池无关。您正在正确关闭 JDBC 资源,但使用的连接池设置不佳。您需要确保连接池保持连接打开的时间不会超过数据库配置的超时时间。减少配置中的一项或增加另一项。
This exception can have 2 causes:
You aren't closing the JDBC resources properly. All of the
Connection
,Statement
andResultSet
must be closed in reversed order in thefinally
block of thetry
block where they're been acquired. This is regardless of the fact whether you're using a connection pool or not.You are closing the JDBC resources properly, but using a connection pool with poor settings. You need to make sure that the connection pool don't hold connections open longer than the DB configrured timeout. Decrease the one or increase the other in the configuration.
我们需要设置以下属性,以避免即使使用连接池也会超时;我们使用 Apache Commons DBCP。
We needed to set the following properties in order to avoid the timeout even with connection pooling; we use the Apache Commons DBCP.