解决这个问题的办法有三种:
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 的配置文件中:
3. 定期使用连接池内的连接,使得它们不会因为闲置超时而被 MySQL 断开。
修改 c3p0 的配置文件,设置:
# Prevent MySQL raise exception after a long idle time
cpool.preferredTestQuery='SELECT 1'
cpool.idleConnectionTestPeriod=18000cpool.testConnectionOnCheckout=true
修改 Spring 的配置文件:
附:以下 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, $1); }
}