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

最近由于业务需要,开发了一个定时程序,每天执行一次,从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进行一次连接可用确认。

测试:

  1. 将mysql的默认时间改为60s,方便测试。(这俩都设置)
set global interactive_timeout=60;
set global wait_timeout=60;
  1. 不设置上面的自动连接确认,隔两分钟请求测试接口。
    第一次请求正常,第二次请求又报上面的错误。
  2. 设置自动连接确认,隔两分钟请求测试接口。
    多次请求均正常。

也可以将上面两个参数设置大一些,比如一年等。需要注意这俩参数的作用级别是“数据库实例”。注意对其他库的影响。

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值