修改資料庫mysql的wait_timeout
最近在測試專案的時候,特別每天第一次測試的時候,總是報資料庫連線不上,連線超時的錯誤,連續連線才能解決問題
類似於一下錯誤
我的理解是wait_timeout設定的是一個訪問等待一個週期時長,比如這個wai_timeout預設是8個小時,如果兩次訪問的時間差大於這個值,就會報連線超時的錯誤。這個是mysql設定的一個connection的空閒時間,超過這個時間,mysql就會主動斷了這個connection,而連線池並不知道該connection已經失效,如果這時有Client請求connection,DBCP將該失效的Connection提供給Client,將會造成異常。
1.mysql分析:
開啟MySQL的控制檯,執行:show variables like ‘%timeout%’,檢視和連線時間有關的MySQL系統變數,得到如下結果:
wait_timeout = 28800ms = 8 hours
其中wait_timeout就是負責超時控制的變數,其時間為長度為28800s,就是8個小時,那麼就是說MySQL的服務會在操作間隔8小時後斷開,需要再次重連。也有使用者在URL中使用jdbc.url=jdbc:mysql://localhost:3306/nd?autoReconnect=true來使得連線自動恢復,當然了,這是可以的,不過是MySQL4及其以下版本適用。MySQL5中已經無效了,必須調整系統變數來控制了。MySQL5手冊中對兩個變數有如下的說明:
interactive_timeout:伺服器關閉互動式連線前等待活動的秒數。互動式客戶端定義為在mysql_real_connect()中使用CLIENT_INTERACTIVE選項的客戶端。又見wait_timeout
wait_timeout:伺服器關閉非互動連線之前等待活動的秒數。線上程啟動時,根據全域性wait_timeout值或全域性interactive_timeout值初始化會話wait_timeout值,取決於客戶端型別(由mysql_real_connect()的連線選項CLIENT_INTERACTIVE定義),又見interactive_timeout
如此看來,兩個變數是共同控制的,那麼都必須對他們進行修改了。繼續深入這兩個變數wait_timeout的取值範圍是1-2147483(Windows),1-31536000(linux),interactive_time取值隨wait_timeout變動,它們的預設值都是28800。
MySQL的系統變數由配置檔案控制,當配置檔案中不配置時,系統使用預設值,這個28800就是預設值。要修改就只能在配置檔案裡修改。Windows下在%MySQL HOME%/bin下有mysql.ini配置檔案,開啟後在如下位置新增兩個變數,賦值。(這裡修改為388000)
解決方法,linux的伺服器上的mysql:
set global interactive_timeout=31536000;
show VARIABLES like '%timeout%';
當只改wait_timeout 是不能改interactive_timeout,但若只改interactive_timeout,wait_timeout 也會跟著改
set interactive_timeout=31536000; 是修改session變數,是不起作用的,當關閉此次會話,再次打開發現還是原來的值