MySQL提示“too many connections”的解决办法

今天生产服务器上的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_connectionswait_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.检查程序代码,对于没有关闭的链接及时进行关闭

posted on 2016-05-23 15:44  yafyr  阅读(286)  评论(0编辑  收藏  举报