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
  • 1
  • 2
  • 3
  • 4

经查发现原来是mysql默认会将8个小时内没有操作过的数据库连接断开。 
项目是springboot。 
找到一个解决办法,在application.properties中设置datasource的时候,加入如下设置: 
(testWhileIdle,validationQuery,timeBetweenEvictionRunsMillis)

dataSource.bySearch.testWhileIdle = true
dataSource.bySearch.validationQuery=SELECT 1
dataSource.bySearch.timeBetweenEvictionRunsMillis = 3600000
  • 1
  • 2
  • 3

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

测试:

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

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

posted on 2017-12-07 10:33  superficial。  阅读(1497)  评论(0编辑  收藏  举报

导航