traceBack:http://hi.baidu.com/lkf0217/blog/item/2169bf2f27e1f33d1e308961.html
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
wait_timeout = 86400
修改 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
# Note: MySQL times out idle connections after 8 hours(28,800 seconds)
# so ensure this value is below MySQL idle timeout
cpool.maxIdleTime=25200
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="maxIdleTime" value="${cpool.maxIdleTime}" />
<!-- other properties -->
</bean>
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="maxIdleTime" value="${cpool.maxIdleTime}" />
<!-- other properties -->
</bean>
修改 c3p0 的配置文件,设置:
# Prevent MySQL raise exception after a long idle time cpool.preferredTestQuery='SELECT 1' cpool.idleConnectionTestPeriod=18000 cpool.testConnectionOnCheckout=true
<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);
}
}
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);
}
}
本文介绍了如何在MySQL默认设置下解决连接超时导致的C3P0连接池返回失效连接的问题,通过调整MySQL的wait_timeout属性、减少连接池内连接的生存周期或定期使用连接池内的连接来避免异常抛出。
1524

被折叠的 条评论
为什么被折叠?



