解决 c3p0 和 MySQL 集成情况下,连接长时间闲置后重新使用时报错的问题

来源:互联网 发布:鞠婧祎 知乎 编辑:程序博客网 时间:2024/05/21 10:35
MySQL 的默认设置下,当一个连接的空闲时间超过8小时后,MySQL 就会断开该连接,而 c3p0 连接池则以为该被断开的连接依然有效。在这种情况下,如果客户端代码向 c3p0 连接池请求连接的话,连接池就会把已经失效的连接返回给客户端,客户端在使用该失效连接的时候即抛出异常。
解决这个问题的办法有三种:
1. 增加 MySQL 的 wait_timeout 属性的值。
修改 /etc/mysql/my.cnf 文件,在 [mysqld] 节中设置:
# Set a connection to wait 8 hours in idle status.
wait_timeout 
= 86400
2. 减少连接池内连接的生存周期,使之小于上一项中所设置的 wait_timeout 的值。
修改 c3p0 的配置文件,设置:
# How long to keep unused connections around(in seconds)
# Note: MySQL times out idle connections after 
8 hours(28,800 seconds)
# so ensure this value is below MySQL idle timeout
cpool.maxIdleTime
=25200
在 Spring 的配置文件中:
<bean id="dataSource"
    class
="com.mchange.v2.c3p0.ComboPooledDataSource">
    
<property name="maxIdleTime" value="${cpool.maxIdleTime}" />
    
<!-- other properties -->
</bean>
3. 定期使用连接池内的连接,使得它们不会因为闲置超时而被 MySQL 断开。
修改 c3p0 的配置文件,设置:
# Prevent MySQL raise exception after a long idle time
cpool.preferredTestQuery
='SELECT 1'
cpool.idleConnectionTestPeriod
=18000
cpool.testConnectionOnCheckout
=true
修改 Spring 的配置文件:
<bean id="dataSource"
    class
="com.mchange.v2.c3p0.ComboPooledDataSource">
    
<property name="preferredTestQuery"
        value
="${cpool.preferredTestQuery}" />
    
<property name="idleConnectionTestPeriod"
        value
="${cpool.idleConnectionTestPeriod}" />
    
<property name="testConnectionOnCheckout"
        value
="${cpool.testConnectionOnCheckout}" />
    
<!-- other properties -->
</bean>

附:以下 awk 脚本可以用以将 c3p0.properties 文件中的属性设置转换成为 applicationContext.xml 中 数据库连接池 DataSource 所需的 XML 元素形式。
#!/bin/awk

BEGIN {
    FS
="=";
}
{
    
if (NF == 2) {
        
if ((x=index($1, ".")) > 0) {
            property_name 
= substr($1, x+1, length($1));
        } 
else {
            property_name 
= $1;
        }
        printf
("<property name="%s" value="${%s}"/> ", property_name, $1);
    }
}