Mysql報too many connections詳解

用過mysql的小夥伴們,大部分都會碰到應用程序或者數據庫維護人員鏈接數據庫的時候,報too many connections的錯誤,這個錯誤是怎麼產生的,該如何解決呢,下面就給你們進行詳細解答mysql

下面是個人mysql 5.7的測試環境,查看一下和鏈接相關的參數配置sql

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錯誤了,這個時候管理員去數據庫進行定位,是什麼緣由致使的這個報錯,看看能不能鏈接上數據庫socket

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連看數據庫性能的機會都沒有了。測試

喜歡的同窗能夠關注個人公衆號(db_arch)(Mysql數據庫運維與架構設計)

喜歡的同窗能夠關注個人公衆號(db_arch)(Mysql數據庫運維與架構設計)spa

相關文章
相關標籤/搜索