Mysql报too many connections详解

用过mysql的小伙伴们,大部分都会碰到应用程序或者数据库维护人员连接数据库的时候,报too many connections的错误,这个错误是怎么产生的,该如何解决呢,下面就给大家进行详细解答

下面是我的mysql 5.7的测试环境,查看一下和连接相关的参数配置

mysql> show variables like '%connections%';
+----------------------+-------+
| Variable_name        | Value |
+----------------------+-------+
| max_connections      | 500   |
| max_user_connections | 0     |
+----------------------+-------+
2 rows in set (0.01 sec)

为了尽快让数据库连接耗尽,我在这里会修改一下参数配置

mysql> set global max_connections=3;
Query OK, 0 rows affected (0.00 sec)

mysql> show variables like '%connections%';
+----------------------+-------+
| Variable_name        | Value |
+----------------------+-------+
| max_connections      | 3     |
| max_user_connections | 0     |
+----------------------+-------+
2 rows in set (0.01 sec)

设置了用户最大连接数为3,下面使用一个普通用户(tony)进行测试

mysql> select * from performance_schema.users;
+------+---------------------+-------------------+
| USER | CURRENT_CONNECTIONS | TOTAL_CONNECTIONS |
+------+---------------------+-------------------+
| NULL |                  28 |            636237 |
| tony |                   2 |           5071859 |
| root |                   1 |                44 |
+------+---------------------+-------------------+
3 rows in set (0.00 sec)

可以看到tony用户的连接到2个了,加上root用户,总的连接数据已经达到3个了,如果再使用tony用户进行连接库,会发生什么呢

[root@cbov10-tidb57-206 ~]# /u02/mysql/bin/mysql --socket=/u02/run/3308/mysql.sock -utony -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1040 (08004): Too many connections

已经开始报too many connections错误了,这个时候管理员去数据库进行定位,是什么原因导致的这个报错,看看能不能连接上数据库

mysql> select * from performance_schema.users;
+------+---------------------+-------------------+
| USER | CURRENT_CONNECTIONS | TOTAL_CONNECTIONS |
+------+---------------------+-------------------+
| NULL |                  28 |            637195 |
| tony |                   2 |           5071860 |
| root |                   2 |                49 |
+------+---------------------+-------------------+
3 rows in set (0.00 sec)

到这里,细心的同学已经发现问题了,tony用户和root用户连接数据已经超过max_connections定义的阀值3了,多了1个,这是怎么回事,难道是这个参数不起作用吗,那如果再用root用户连接数据库,看看时候能连接数据库

[root@cbov10-tidb57-206 ~]# /u02/mysql/bin/mysql --socket=/u02/run/3308/mysql.sock -uroot -proot
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1040 (HY000): Too many connections

这个时候root用户也无法连接了,在这里解释一下为什么总连接数会超一个,原来mysql数据库在max_connections之外,额外提供一个连接,提供给super权限用户进行故障诊断使用,所以大家在使用mysql数据库的时候,应用程序千万别用root去连接数据库,一旦发生问题,dba连看数据库性能的机会都没有了。

https://mp.weixin.qq.com/s/kPJhMUqxJKcZkqv6IKr4AA

猜你喜欢

转载自blog.csdn.net/qq_40907977/article/details/114867981