1. 程式人生 > >記一次CentOS7-MySQL排坑歷程

記一次CentOS7-MySQL排坑歷程

一、報錯及起因

今天在 CentOS7 中安裝了 mysql5.7,然後為了測試資料庫環境是否配置成功,便寫了個基於 mybatis+Spring 的 java web 程式連線操作 mysql 資料庫,於是就一些發生了令人感到很煩的報錯和故事:

當程式涉及到關於資料庫的操作如查詢、插入等操作時,首先瀏覽器訪問會很慢,進度條一直旋轉,然後頁面會報 500 錯誤:org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exception 。然而我在 CentOS7 服務端和 Windows 本地的 Navicat 連線 mysql 都沒問題。。。

mysql海豚

二、排錯歷程

1.檢查 sql 語句

看著這似乎是 mybatis 引起的錯誤,所以先檢查 mapper 的 xml 中 sql 語句是否有錯誤,例如引數的格式轉化、resultType 為 JavaBean、resultMap 需要定義、JavaBean 和 dao 的引入等。

檢查中並沒有發現什麼問題,而且錯誤仍然存在。

2. MySql Host is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts' 報錯

原因分析:

檢視 tomcat 的日誌檔案,發現在報錯開始部分出現了這個錯誤。經過查詢,發現這個錯誤的 原因

是:同一個 ip 在短時間內產生太多(超過 mysql 資料庫 max_connection_errors 的最大值)中斷的資料庫連線而導致的阻塞。

解決方法:

進入 CentOS7 伺服器:

方法一:提高允許的max_connection_errors數量(治標不治本):

  1. 進入 Mysql 資料庫檢視 max_connection_errors: show variables like '%max_connection_errors%';
  2. 修改 max_connection_errors 的數量為 1000: set global max_connect_errors = 1000;
  3. 檢視是否修改成功:show variables like '%max_connection_errors%';

方法二:使用 mysqladmin flush-hosts 命令清理一下 hosts 檔案:

  1. 查詢 mysqladmin 的路徑:whereis mysqladmin
  2. 執行命令,如:/usr/local/mysql5.5.35/bin/mysqladmin -uroot -pyourpwd flush-hosts

注: 方法二清理 hosts 檔案,也可以直接進入 mysql 資料庫執行命令:mysql> flush hosts;

3.com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure 異常

解決了 hosts 的問題後,在 tomcat 的日誌檔案,發現在報錯開始部分又出現了這個錯誤:

 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet successfully received from the server was 32 milliseconds ago.  The last packet sent successfully to the server was 32 milliseconds ago.
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
	at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:990)
	......

原因分析:

表示程式與 MySQL 通訊失敗了,即連線失敗了。The last packet successfully received from the server was 32 milliseconds ago 表示 mysql 重連,連線丟失。此為資料庫連線空閒回收問題,程式開啟資料庫連線後,等待做資料庫操作時,發現連線被 MySQL 關閉掉了。

認為可能是連線等待超時問題。在 mysql 資料庫的配置中,其連線的等待時間(wait_timeout)預設值為 8 小時。在 mysql 中可以檢視:

mysql﹥ 
mysql﹥ show global variables like 'wait_timeout'; 
+---------------+---------+ 
| Variable_name | Value | 
+---------------+---------+ 
| wait_timeout | 28800 | 
+---------------+---------+ 
1 row in set (0.00 sec) 

28800 seconds,也就是8小時。如果在 wait_timeout 秒期間內,資料庫連線(java.sql.Connection)一直處於等待狀態,mysql 就將該連線關閉。這時,Java 應用的連線池仍然合法地持有該連線的引用。當用該連線來進行資料庫操作時,就碰到上述錯誤。

MySQL 連線一次連線需求會經過 6 次「握手」方可成功,任何一次「握手」失敗都可能導致連線失敗。前三次握手可以簡單理解為 TCP 建立連線所必須的三次握手,MySQL 無法控制,更多的受制於 tcp 協議的不同實現,後面三次握手過程超時與 connect_timeout 有關。

解決方法:

改變資料庫引數是最簡單的處理方式(修改 /etc/my.cnf 中的 wait_timeout 值),但是需要重啟資料庫,影響較大。在不修改資料庫引數的前提下,可以做已下處理:

  • 如果使用的是 jdbc ,在 jdbc url 上新增 autoReconnect=true ,如:dataSource.url=jdbc:mysql://132.231.xx.xxx:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=true&autoReconnect=true

  • 如果是在 Spring 中使用 DBCP 連線池,在定義 datasource 增加屬性 validationQuery 和 testOnBorrow ,如:

    <bean id="vrsRankDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${dataSource.driver}"/>
        <property name="url" value="${dataSource.url}"/>
        <property name="username" value="${dataSource.user}"/>
        <property name="password" value="${dataSource.password}"/>
        <property name="validationQuery" value="SELECT 1"/>
        <property name="testOnBorrow" value="true"/>
    </bean>
    
  • 如果是在 Spring 中使用 c3p0 連線池,則在定義 datasource 的時候,新增屬性 testConnectionOnCheckin 和 testConnectionOnCheckout ,如:

    <bean name="cacheCloudDB" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${dataSource.driver}"/>
        <property name="jdbcUrl" value="${dataSource.url}"/>
        <property name="user" value="${dataSource.user}"/>
        <property name="password" value="${dataSource.password}"/>
        <property name="initialPoolSize" value="10"/>
        <property name="maxPoolSize" value="10"/>
        <property name="testConnectionOnCheckin" value="false"/>
        <property name="testConnectionOnCheckout" value="true"/>
        <property name="preferredTestQuery" value="SELECT 1"/>
    </bean>
    

4. 遠端連線 Mysql 太慢問題

嘗試解決了一下上面的連線超時問題,但是發現並沒有什麼用,還是會出現上面的問題。於是便懷疑是不是遠端連線 Mysql 太慢導致了連線超時?因為我在 CentOS7 服務端和 Windows 本地的 Navicat 連線 mysql 都沒問題。在網上查詢了下,發現在 mysql 的配置檔案 /etc/my.cnf 中增加如下配置引數:

# 注意該配置是加在[mysqld]下面
[mysqld]
skip-name-resolve

然後需要重啟 mysql 服務。因為根據說明,如果 mysql 主機查詢和解析 DNS 會導致緩慢或是有很多客戶端主機時會導致連線很慢。同時,請注意在增加該配置引數後,mysql的授權表中的host欄位就不能夠使用域名而只能夠使用ip地址了,因為這是禁止了域名解析的結果。

5. 終極解決:Could not create connection to database server. Attempted reconnect 3 times. Giving up 報錯

原因分析:

經過上面的配置後,重新測試程式,就又出現了這個錯誤。經過查詢,發現這是由於 SSL 引起的錯誤。因為我是在 CentOS7 上使用 yum 命令新裝的 MySQL5.7,預設是沒有配置 MySQL SSL 的。

而我以前一直使用的 Ubuntu16.04 上的 mysql 資料庫,它預設是配置了 MySQL SSL 的,所以我習慣在連線資料庫的 jdbc 的 url 裡面加上 &useSSL=true ,即使用 SSL 加密。導致我在連線當前 mysql 的時候,一直連線不上。檢視 tomcat 日誌的報錯末尾,會有如下報錯:

Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
	at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
	at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:310)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1639)
	at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223)
	at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037)
	at sun.security.ssl.Handshaker.process_record(Handshaker.java:965)
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064)
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
	at com.mysql.jdbc.ExportControlled.transformSocketToSSLSocket(ExportControlled.java:186)
	... 24 more
Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
	at com.mysql.jdbc.ExportControlled$X509TrustManagerWrapper.checkServerTrusted(ExportControlled.java:302)
	at sun.security.ssl.AbstractTrustManagerWrapper.checkServerTrusted(SSLContextImpl.java:1091)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1621)
	... 32 more
Caused by: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
	at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:154)
	at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:80)
	at java.security.cert.CertPathValidator.validate(CertPathValidator.java:292)
	at com.mysql.jdbc.ExportControlled$X509TrustManagerWrapper.checkServerTrusted(ExportControlled.java:295)
	... 34 more

遂恍然大悟。。。

解決方法:

在配置 JDBC URL 時使用 &useSSL=false ,即不使用 SSL 加密,配置後連線正常:

dataSource.url = jdbc:mysql://132.231.xx.xxx:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true

如果安全性較高的資料建議在 MySQL 端還是把 SSL 配上。

三、總結

由於 MySQL 的 SSL 問題引起了一連串的問題。由於 SSL 加密的問題,導致程式向 mysql 的連線超時,然後一直向 mysql 傳送連線,導致了同一個 ip 在短時間內產生太多中斷的資料庫連線而導致的阻塞。

以後看報錯日誌,除了看報錯的最開始部分,也要看看報錯的結尾部分,弄不好會有一些其他的發現的。


PS:如果覺得文章有什麼地方寫錯了,哪裡寫得不好,或者有什麼建議,歡迎指點。

歡迎您的點贊、收藏