解決這個問題的辦法有三種:
1. 增加 MySQL 的 wait_timeout 屬性的值。
修改 /etc/mysql/my.cnf 文件,在 [mysqld] 節中設置:
wait_timeout = 86400
修改 c3p0 的配置文件,設置:
# Note: MySQL times out idle connections after 8 hours(28,800 seconds)
# so ensure this value is below MySQL idle timeout
cpool.maxIdleTime=25200
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 元素形式。
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);
}
}