Mysql上线长时间以后重新发起请求报错

本文探讨了MySQL连接池的机制,特别是在连接闲置超过八小时后自动断开的问题。介绍了如何通过配置testOnBorrow、validationQuery和testWhileIdle等参数来增强连接池的稳定性和性能,避免Web应用因无效连接而报错。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mysql机制及错误原因:当连接闲置超过八小时后,mysql会自动断开连接,此时连接失效,但是数据库认为此时连接依然有效,连接的时候发现失效,报错。
解决办法:增加对连接池中连接的测试/验证,防止数据库认为连接已死而Web应用服务器认为连接还有效
添加参数:
testOnBorrow:检测池里连接的可用性 设置为true是会见降低性能
validationQuery:验证数据库连接的查询语句
testWhileIdle:建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。

public static final String DBDRIVER = "com.mysql.jdbc.Driver";
public static final String DBURL = "jdbc:mysql://xxx.xxx.xx.xx:3306/omslocal?useSSL=false&autoReconnect=true&testWhileIdle=true&testOnBorrow=true&validationQuery=select 1"; //考虑性能,此处请酌情修改 
public static final String DBUSER = "xxx";
public static final String PASSWORD = "xxx";

public static java.sql.Connection connection = null;
public static java.sql.PreparedStatement preparedStatement = null;
public static java.sql.ResultSet resultSet = null;

public static String getConnection() {
    try {
        Class.forName(DBDRIVER);
        DriverManager.setLoginTimeout(5);
        connection = DriverManager.getConnection(DBURL, DBUSER, PASSWORD);
        return "success";
    } catch (ClassNotFoundException e) {
        return "ClassNotFoundException";
    } catch (SQLException e) {
        return  e.toString();
    }
}

参考配置:

<!--initialSize: 初始化连接-->  
<property name="initialSize" value="5"/>  

<!--maxIdle: 最大空闲连接-->  
<property name="maxIdle" value="10"/>  

<!--minIdle: 最小空闲连接-->  
<property name="minIdle" value="5"/>  

<!--maxActive: 最大连接数量-->  
<property name="maxActive" value="15"/>  

<!--removeAbandoned: 是否自动回收超时连接-->  
<property name="removeAbandoned" value="true"/>  

<!--removeAbandonedTimeout: 超时时间(以秒数为单位)-->  
<property name="removeAbandonedTimeout" value="180"/>  

<!--maxWait: 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒-->  
<property name="maxWait" value="3000"/>  

<property name="validationQuery">  
<value>SELECT 1</value>  
</property>  

<property name="testOnBorrow">  
<value>true</value>  
</property>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值