一.報錯的問題:
測試環境在做壓力測試的時候爆出錯誤
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
INFO | jvm 1 | 2013/10/24 14:22:28 |
INFO | jvm 1 | 2013/10/24 14:22:28 | The last packet successfully received from the server was 26,071 milliseconds ago. The last packet sent successfully to the server was 0 milliseconds ago.
INFO | jvm 1 | 2013/10/24 14:22:28 |
二.解決問題:
先看看MySQL服務器默認的“wait_timeout”是120秒,意味着如果一個連接的空閑時間超過120秒,MySQL將自動斷開該連接,而連接池卻認為該連接還是有效的(因為並未校驗連接的有效性),當應用申請使用該連接時,就會導致上面的報錯。
mysql> show global variables like 'wait_timeout';
+----------------------------+-------+
| Variable_name | Value |
+----------------------------+-------+
| wait_timeout | 120 |
+----------------------------+-------+
----------------------------------------------------------
MySQL連接如果8小時未使用,在查詢使用到該連接會報:
異常名稱:com.mysql.jdbc.CommunicationsException
異常信息: Communications link failure due to underlying exception
如果是MySQL5以前的版本,需要修改連接池配置中的URL,添加autoReconnect=true
如果是MySQL5 以后的版本,需要修改my.cnf(或者my.ini)文件,在[mysqld]后面添加
wait_timeout = 172800
interactive-timeout = 172800
單位都是秒,記得必須都添加,否則不起作用,通過show variables查看wait_timeout的值
-----------------------------------------
由於項目中使用的是c3p0連接池,c3p0配置需查看這些屬性是否已經加上。
<!--如果設為true那么在取得連接的同時將校驗連接的有效性。Default: false -->
<property name="testConnectionOnCheckin">true</property>
<!--因性能消耗大請只在需要的時候使用它。如果設為true那么在每個connection提交的
時候都將校驗其有效性。建議使用idleConnectionTestPeriod或automaticTestTable
等方法來提升連接測試的性能。Default: false -->
<property name="testConnectionOnCheckout">false</property>
<!--每60秒檢查所有連接池中的空閑連接。Default: 0 -->
<property name="idleConnectionTestPeriod">60</property>
<!--最大空閑時間,60秒內未使用則連接被丟棄。若為0則永不丟棄。Default: 0 -->
<property name="maxIdleTime">60</property>
具體參數詳見:http://blog.csdn.net/yougou_sully/article/details/13430405
官方參數詳見:http://www.mchange.com/projects/c3p0/index.html