標籤:
今天生產伺服器上的MySQL出現了一個不算太陌生的錯誤“Too many connections”。平常碰到這個問題,我基本上是修改/etc/my.cnf的max_connections參數,然後重啟資料庫。但
是生產伺服器上資料庫又不能隨便重啟。
沒辦法,只好想辦法手動去釋放一些沒用的串連。
登陸到MySQL的提示符下,資料show processlist這個命令,可以得到所以串連到這個伺服器上的MySQL串連:
mysql> show processlist;
+---------+------+---------------------+---------+---------+------+-------+-------------------+
| 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號(在上表的第一列)。我們只要輸入這樣的命令:
mysql> kill 1180421;
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.檢查程式碼,對於沒有關閉的連結及時進行關閉
MySQL提示“too many connections”的解決辦法