数据库连接池配置解决mysql 8小时断开连接问题

问题:

mysql 8小时断开连接问题:mysql的默认设置下,当一个连接的空闲时间超过8小时后,mysql 就会断开该连接,而连接池认为连接依然有效。在这种情况下,如果客户端代码向连接池请求连接的话,连接池就会把已经失效的连接返回给客户端,客户端在使用该失效连接的时候即抛出异常。

解决方案:

可以通过数据库连接池的配置来解决此问题。下面通过例子进行说明为了便于模拟,首先将数据库的最大超时时间改为10s,也就是说10s空闲后就会超时断开,如下:

使用dbcp的连接池(使用其他的如c3p0、druid连接池情况类似)。

配置一:

 <bean id="dataSource"
     class="org.apache.commons.dbcp2.BasicDataSource"
     destroy-method="close">
     <property name="url" value="jdbc:mysql://localhost:3306/test"/>
     <property name="username" value="root"/>
     <property name="password" value="root"/>
     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
     <property name="testOnBorrow" value="true"/> //默认值
public class Main {

    public static void main(String[] args) throws BeansException, Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-context*.xml");
        //测试mybatis
        System.out.println(context.getBean(TestDao.class).getAll());
        Thread.sleep(15000);
        System.out.println(context.getBean(TestDao.class).getAll());
    }
}

执行测试方法,间隔15s执行的两次查询都执行成功。

分析:

<property name="testOnBorrow" value="true"/>,此处为了更清楚地说明testOnBorrow的效果,特别显式的进行了配置,其实dbcp对testOnBorrow默认的配置就是true。

这个配置的意思是每次取一个连接的时候都要进行测试,这样就能避免出现异常的情况。

配置二:

 <bean id="dataSource"
     class="org.apache.commons.dbcp2.BasicDataSource"
     destroy-method="close">
     <property name="url" value="jdbc:mysql://localhost:3306/test"/>
     <property name="username" value="root"/>
     <property name="password" value="root"/>
     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
     <property name="testOnBorrow" value="false"/>

将testOnBorrow设置为false,每次取出连接时不进行判断,测试结果,报错:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure。

将testOnBorrow设置为true或者使用默认配置能解决mysql 8小时问题,但每次取连接都进行一次测试的方式在请求量特别大的情况下性能是不佳的,于是出现了下面的方案。

配置三:

 <bean id="dataSource"
     class="org.apache.commons.dbcp2.BasicDataSource"
     destroy-method="close">
     <property name="url" value="jdbc:mysql://localhost:3306/test"/>
     <property name="username" value="root"/>
     <property name="password" value="root"/>
     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
     <property name="testOnBorrow" value="false"/>
     <property name="validationQuery" value="select 1"/>
     <property name="testWhileIdle" value="true"/>
     <property name="timeBetweenEvictionRunsMillis" value="5000"/>

执行测试方法,间隔15s执行的两次查询都执行成功。

分析:

testWhileIdle设置为true,即空闲时对连接进行测试,timeBetweenEvictionRunsMillis即空闲5000ms进行一次测试,validationQuery即进行测试时执行的语句。所以只要

timeBetweenEvictionRunsMillis时间间隔小于数据库设置的超时时间间隔(5s<10s),就能避免8小时断开连接问题。实际环境中根据数据库配置的超时时间,配置相应的

timeBetweenEvictionRunsMillis即可。比如数据库8小时断开连接,我们配置timeBetweenEvictionRunsMillis为1小时。

 
原文地址:https://www.cnblogs.com/silenceshining/p/12570924.html