項目使用springBoot作為框架,使用Druid數據源,使用mysql版本為5.6。
線上出現錯誤
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
在網上了解到:出現鏈接中斷的原因是:mysql會中斷l在一段時間內一直保持的空閑的連接,而連接池並沒有拋棄任何的空閑連接。所以當程序在達到請求數據庫的代碼時,如果連接池將已經中斷的連接分配給線程,就會出現link failer錯誤。
使用mysql4版本的,可以在url中使用autoReconnet設置自動連接:url=jdbc:mysql://localhost:3306/test?autoReconnect=true。
但是到了mysql5,autoReconnect就失效了。
解決辦法:
辦法一:修改mysql的內置變量。
查詢timeout變量:使用語句show variables like '%timeout%'; 會出現與timeout相關的變量。
這里面,我們僅需要關注兩個變量:wait_timeout、interactive_timeout。它們默認都是8小時。最大值是一年。一定要將這兩個變量一起改,使用語句set gloal variables wait_timeout = 28800;
改變之后要記得重啟mysql才可以。
辦法二:修改代碼層面連接池配置。下面貼出可用的springboot配置

1 sharding: 2 jdbc: 3 datasource: 4 names: master 5 master: 6 type: com.alibaba.druid.pool.DruidDataSource 7 driver-class-name: com.mysql.jdbc.Driver 8 url: jdbc:mysql://localhost:3358/test 9 username: root 10 password: 123456 11 #自動檢測連接開關 12 testWhileIdle: true 13 #檢測語句 14 validationQuery: select 1 15 #配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 16 #因為我自己配置的是空閑連接1分鍾斷開,所以此處測試連接間隔為55s 17 timeBetweenEvictionRunsMillis: 55000