您的位置:首页 > 编程语言 > Java开发

mysql数据库连接超过8小时失效的解决方案(springboot)

2017-03-14 19:49 316 查看
最近由于业务需要,开发了一个定时程序,每天执行一次,从mysql库里取出数据处理。这是前提。

结果今天早上查看错误日志,发现了如下的日志:

2017-03-12 03:00:02.539 ERROR 9311 --- [nio-9000-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed;
nested exception is org.springframework.dao.RecoverableDataAccessException: StatementCallback; SQL [DELETE FROM search_product];
The last packet sent successfully to the server was 86,395,487 milliseconds ago.
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.] with root cause


经查发现原来是mysql默认会将8个小时内没有操作过的数据库连接断开。

项目是springboot。

找到一个解决办法,在application.properties中设置datasource的时候,加入如下设置:

(testWhileIdle,validationQuery,timeBetweenEvictionRunsMillis)

dataSource.bySearch.testWhileIdle = true
dataSource.bySearch.validationQuery=SELECT 1
dataSource.bySearch.timeBetweenEvictionRunsMillis = 3600000


它的作用就是会每隔一小时向mysql进行一次连接可用确认。

测试:

将mysql的默认时间改为60s,方便测试。(这俩都设置)

set global interactive_timeout=60;
set global wait_timeout=60;


不设置上面的自动连接确认,隔两分钟请求测试接口。

第一次请求正常,第二次请求又报上面的错误。

设置自动连接确认,隔两分钟请求测试接口。

多次请求均正常。

也可以将上面两个参数设置大一些,比如一年等。需要注意这俩参数的作用级别是“数据库实例”。注意对其他库的影响。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: