使用Connector/J連接MySQL數據庫,程序運行較長時間后就會報以下錯誤:
Communications link failure,The last packet successfully received from the server was * **millisecond ago.
The last packet successfully sent to the server was * **millisecond ago。
其中錯誤還會提示你修改wait_timeout或是使用Connector/J的autoReconnect屬性避免該錯誤。
后來查了一些資料,才發現遇到這個問題的人還真不少,大部分都是使用連接池方式時才會出現這個問題,短連接應該很難出現這個問題。這個問題的原因:
-
按照錯誤的提示,可以在JDBC URL中使用autoReconnect屬性,實際測試時使用了autoReconnect=true&failOverReadOnly=false,不過並未起作用,使用的是5.1版本,可能真像網上所說的只對4之前的版本有效。
-
沒辦法,只能修改MySQL的參數了,wait_timeout最大為31536000即1年,在my.cnf中加入:
[mysqld]
wait_timeout=31536000
interactive_timeout=31536000
- 1
重啟生效,需要同時修改這兩個參數。
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
[09:49:36.821]
[09:49:36.821]Last packet sent to the server was 0 ms ago.