Spring Boot:在使用 Hibernate、JDBC 和 MySQL 几个小时不活动后通信链接失败 [重复]

Posted

技术标签:

【中文标题】Spring Boot:在使用 Hibernate、JDBC 和 MySQL 几个小时不活动后通信链接失败 [重复]【英文标题】:Spring Boot: Communications link failure after some hours of inactivity with Hibernate, JDBC and MySQL [duplicate] 【发布时间】:2015-07-31 22:39:59 【问题描述】:

如果我的 Spring Boot 应用程序在几个小时内处于非活动状态(例如在夜间),我会收到此错误:

2015-05-19 09:16:32.666  WARN 20582 --- [http-nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 08S01
2015-05-19 09:16:32.668 ERROR 20582 --- [http-nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : Communications link failure

The last packet successfully received from the server was 29.792.613 milliseconds ago.  The last packet sent successfully to the server was 6 milliseconds ago.

为了解决这个问题,我读到 MySQL 有一个名为 wait_timeout 的参数默认设置为 8 小时(28800 秒),在此之后我所有的非活动连接都关闭了,所以我的 Spring启动应用程序停止工作...

我的问题是:

如何避免这个问题? 我应该增加此类参数的值吗? 增加这种价值有什么缺点吗? (如果我的应用程序长时间处于非活动状态,它可能始终是我的应用程序达到的值..:/) 是否还有其他使用 Spring Boot 的解决方案(如轮询或类似的东西)?

编辑

这里还有其他类似/有用的问题:

Hibernate Communications Link Failure in Hibernate Based Java Servlet application powered by mysql Spring is losing connection to the DB and does not recover or reconnect WARN SqlExceptionHelper:143 - SQL Error: 0, SQLState: 08S01- SqlExceptionHelper:144 - Communications link failure SQL Error: 0, SQLState: 08S01 Communications link failure https://serverfault.com/questions/89955/unable-to-connect-to-mysql-through-jdbc-connector-through-tomcat-or-externally Solving a "communications link failure" with JDBC and MySQL

从上面的参考资料我可以得出结论,一种解决方案是将 C3p0 添加为附加库并正确配置它以避免通信链接错误..

这是我唯一的解决方案吗?没有与 Spring/Spring Boot 更“集成”的解决方案(即不添加外部库)吗?

【问题讨论】:

您应该阅读 C3P0 cmets。对您的连接 URL 进行了 MySQL 调整和调整(验证查询和自动重新连接是最重要的)。 感谢@M.Deinum 的建议。在这里阅读***.com/questions/667289/…,似乎不推荐在连接字符串中设置autoReconnect。所以我将尝试为我的数据源使用一些选项:testWhileIdletimeBetweenEvictionRunsMillisvalidationQuery。但是我仍在等待一些好的和“确定的”答案:) 【参考方案1】:

我解决了这里描述的问题: http://blog.netgloo.com/2015/07/09/spring-boot-communications-link-failure-with-mysql-and-hibernate/ ,在application.properties 文件中添加这些配置:

spring.datasource.tomcat.testWhileIdle = true
spring.datasource.tomcat.timeBetweenEvictionRunsMillis = 60000
spring.datasource.tomcat.validationQuery = SELECT 1

【讨论】:

以上是关于Spring Boot:在使用 Hibernate、JDBC 和 MySQL 几个小时不活动后通信链接失败 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

在 Spring Boot 中使用 Hibernate 为 DAO 层配置单元测试

Spring Boot:在单元测试中使用 Hibernate Session

JPA Spring Boot Hibernate Rest API:为啥Hibernate在插入之前会删除?

无法使用 Hibernate 在 Spring Boot 中将 MongoDB 设置为自动递增

Spring Boot / JPA / Hibernate,如何根据 Spring 配置文件切换数据库供应商?

JTAC 在 Spring Boot 中是不是推荐与 Hibernate 一起使用