MySQL 的默認設置下,當一個連接的空閑時間超過8小時后,MySQL 就會斷開該連接,而 c3p0 連接池則以為該被斷開的連接依然有效。在這種情況下,如果客戶端代碼向 c3p0 連接池請求連接的話,連接池就會把已經(jīng)失效的連接返回給客戶端,客戶端在使用該失效連接的時候即拋出異常。
這就是傳說中的 mySql 8小時問題。
解決這個問題的辦法有三種:
1. 增加 MySQL 的 wait_timeout 屬性的值。
修改 /etc/mysql/my.cnf 文件,在 [mysqld] 節(jié)中設置:
# Set a connection to wait 8 hours in idle status.
wait_timeout = 86400 相關參數(shù),紅色部分
mysql> show variables like '%timeout%';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| wait_timeout | 28800 |
+--------------------------+-------+
同一時間,這兩個參數(shù)只有一個起作用。到底是哪個參數(shù)起作用,和用戶連接時指定的連接參數(shù)相關,缺省情況下是使用wait_timeout。我建議是將這兩個參數(shù)都修改,以免引起不必要的麻煩。
這兩個參數(shù)的默認值是8小時(60*60*8=28800)。
測試將這兩個參數(shù)改為0,結果出人意料,系統(tǒng)自動將這個值設置為28800 。
換句話說,不能將該值設置為永久。
將這2個參數(shù)設置為1年(60*60*24*365=31536000)
總不至于一年都不用這個鏈接吧?
set interactive_timeout=31536000;
set wait_timeout=31536000;
結果:
wait_timeout 的設置出現(xiàn)警告,再看看設置后的結果
也就是說wait_timeout的最大值只允許2147483 (24天左右)
。。。。。。
2. 減少連接池內(nèi)連接的生存周期,使之小于上一項中所設置的 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. 定期使用連接池內(nèi)的連接,使得它們不會因為閑置超時而被 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>