MySQL提示「too many connections」的解決辦法 2

今天生產服務器上的MySQL出現了一個不算太陌生的錯誤「Too many connections」。日常碰到這個問題,我基本上是修改/etc/my.cnf的max_connections參數,而後重啓數據庫。但
是生產服務器上數據庫又不能隨便重啓。mysql

沒辦法,只好想辦法手動去釋放一些沒用的鏈接。
登錄到MySQL的提示符下,數據show processlist這個命令,能夠獲得因此鏈接到這個服務器上的MySQL鏈接:sql

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 的值越大,鏈接的空閒等待就越長,這樣就會形成當前鏈接數越大。code

解決方法:orm

修改MySQL配置文件/etc/my.cnf,設置成max_connections=1000,wait_timeout=5。若是沒有此項設置能夠自行添加,修改後重啓MySQL服務便可。要不常常性報此錯誤,則要對服務器做總體性能優化server


 

注:

爲了防止發生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.檢查程序代碼,對於沒有關閉的連接及時進行關閉

相關文章
相關標籤/搜索