今天生產服務器上的MySQL出現了一個不算太陌生的錯誤“Too many connections”。平常碰到這個問題,我基本上是修改/etc/my.cnf的max_connections參數,然后重啟數據庫。但
是生產服務器上數據庫又不能隨便重啟。
沒辦法,只好想辦法手動去釋放一些沒用的連接。
登陸到MySQL的提示符下,數據show processlist這個命令,可以得到所以連接到這個服務器上的MySQL連接:
+---------+------+---------------------+---------+---------+------+-------+-------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------+---------------------+---------+---------+------+-------+-------------------+
| 1180421 | ur | 202.103.96.68:49754 | test1 | Sleep | 1 | | NULL |
| 1180427 | ur | 202.103.96.68:55079 | test2 | Sleep | 1 | | NULL |
| 1180429 | ur | 202.103.96.68:55187 | testdba | Sleep | 0 | | NULL |
| 1180431 | ur | 202.103.96.68:55704 | testdba | Sleep | 0 | | NULL |
| 1180437 | ur | 202.103.96.68:32825 | test1 | Sleep | 1 | | NULL |
| 1180469 | ur | 202.103.96.68:58073 | testdba | Sleep | 0 | | NULL |
| 1180472 | ur | 83.136.93.131:47613 | test2 | Sleep | 8 | | NULL |
| 1180475 | root | localhost | NULL | Query | 0 | NULL | show PROCESSLIST |
+---------+------+---------------------+---------+---------+------+-------+-------------------+
8 rows in set (0.00 sec)
mysql>
然后,你可以看到像上面這樣的MySQL數據連接列表,而且每一個都會有一個進程ID號(在上表的第一列)。我們只要輸入這樣的命令:
Query OK, 0 rows affected (0.00 sec)
mysql>
其中1180421為你在進程列表里找到並且要殺掉的進程號。
產生這種問題的原因是:
連接數超過了 MySQL 設置的值,與 max_connections 和 wait_timeout 都有關系。wait_timeout 的值越大,連接的空閑等待就越長,這樣就會造成當前連接數越大。
解決方法:
修改MySQL配置文件/etc/my.cnf,設置成max_connections=1000,wait_timeout=5。如果沒有此項設置可以自行添加,修改后重啟MySQL服務即可。要不經常性報此錯誤,則要對服務器作整體性能優化
注:
為了防止發生too many connections時候無法登錄的問題,mysql manual有如下的說明:
mysqld actually allows max_connections+1
clients to connect. The extra connection is reserved for use by accounts that have the SUPER
privilege. By granting the SUPER
privilege to administrators and not to normal users (who should not need it), an administrator can connect to the server and use SHOW PROCESSLIST
to diagnose problems even if the maximum number of unprivileged clients are connected.
因此, 必須只賦予root用戶的SUPER權限,同時所有數據庫連接的帳戶不能賦予SUPER權限。前面說到的報錯后無法登錄就是由於我們的應用程序直接配置的root用戶
總結,解決問題的最終方法:
1.修改配置文件/etc/my.cnf,調整連接參數
2.檢查程序代碼,對於沒有關閉的鏈接及時進行關閉