在弹簧引导jpahibernate时,连接到Db后大于4 <24

我有一个应用程序,使用spring-boot,jpa-hiberanate和mysql.I得到这个错误日志

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 56,006,037 milliseconds ago. The last packet sent successfully to the server was 56,006,037 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. 

这是我的application.properties

 # DataSource settings: set here configurations for the database connection spring.datasource.url = jdbc:mysql://localhost:3306/test spring.datasource.username = test spring.datasource.password = test spring.datasource.driverClassName = com.mysql.jdbc.Driver # Specify the DBMS spring.jpa.database = MYSQL # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate settings are prefixed with spring.jpa.hibernate.* spring.jpa.hibernate.ddl-auto = update spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy 

为了解决这个问题,我可以使用

 spring.datasource.testOnBorrow=true spring.datasource.validationQuery=SELECT 1 

但我检查了这不是build议 。所以任何人都可以build议我该怎么做来克服这个错误

最简单的方法是在JDBC url中指定autoReconnect属性,虽然这不是推荐的方法。

 spring.datasource.url = jdbc:mysql://localhost:3306/test?autoReconnect=true 

当你有一个活动的连接,并且在一个事务中发生了一些事情,并且重新连接将会发生的时候,这会产生问题。 在事务开始时validation连接并在开始时获取新连接时,不会出现问题。

但是,在应用程序的生命周期中启用对连接的validation可能会更好。 为此,您可以指定几个属性 。

首先通过指定允许池的最大连接数开始。 (关于确定最大池大小阅读此 )。

 spring.datasource.max-active=10 

您也可能要指定初始连接的数量

 spring.datasource.initial-size=5 

接下来,您要指定空闲连接的最小和最大数量。

 spring.datasource.max-idle=5 spring.datasource.min-idle=1 

要validation连接,您需要指定validation查询以及何时validation。 正如你想定期validation,而不是从池中检索连接(这是为了防止池中的连接断开)。

 spring.datasource.test-while-idle=true spring.datasource.test-on-borrow=true spring.datasource.validation-query=SELECT 1 

现在您在连接闲置时也进行了validation,您需要指定您希望为连接运行此查询的频率以及连接被视为空闲的时间。

 spring.datasource.time-between-eviction-runs-millis=5000 (this is the default) spring.datasource.min-evictable-idle-time-millis=60000 (this is also default) 

这一切都应该触发你的(空闲)连接的validation,当发生exception或闲置期已过,你的连接将被从池中删除。

假设你正在使用Tomcat JDBC作为连接池, 这是一个很好的阅读什么和如何configuration。