用過MySQL的小伙伴們,大部分都會碰到應(yīng)用程序或者數(shù)據(jù)庫維護(hù)人員連接數(shù)據(jù)庫的時候,報too many connections的錯誤,這個錯誤是怎么產(chǎn)生的,該如何解決呢,下面就給大家進(jìn)行詳細(xì)解答
下面是我的mysql 5.7的測試環(huán)境,查看一下和連接相關(guān)的參數(shù)配置
mysql> show variables like '%connections%'; +----------------------+-------+ | Variable_name | Value | +----------------------+-------+ | max_connections | 500 | | max_user_connections | 0 | +----------------------+-------+ 2 rows in set (0.01 sec)為了盡快讓數(shù)據(jù)庫連接耗盡,我在這里會修改一下參數(shù)配置
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)設(shè)置了用戶最大連接數(shù)為3,下面使用一個普通用戶(tony)進(jìn)行測試
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用戶,總的連接數(shù)據(jù)已經(jīng)達(dá)到3個了,如果再使用tony用戶進(jìn)行連接庫,會發(fā)生什么呢
[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已經(jīng)開始報too many connections錯誤了,這個時候管理員去數(shù)據(jù)庫進(jìn)行定位,是什么原因?qū)е碌倪@個報錯,看看能不能連接上數(shù)據(jù)庫

到這里,細(xì)心的同學(xué)已經(jīng)發(fā)現(xiàn)問題了,tony用戶和root用戶連接數(shù)據(jù)已經(jīng)超過max_connections定義的閥值3了,多了1個,這是怎么回事,難道是這個參數(shù)不起作用嗎,那如果再用root用戶連接數(shù)據(jù)庫,看看時候能連接數(shù)據(jù)庫
[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用戶也無法連接了,在這里解釋一下為什么總連接數(shù)會超一個,原來mysql數(shù)據(jù)庫在max_connections之外,額外提供一個連接,提供給super權(quán)限用戶進(jìn)行故障診斷使用,所以大家在使用mysql數(shù)據(jù)庫的時候,應(yīng)用程序千萬別用root去連接數(shù)據(jù)庫,一旦發(fā)生問題,dba連看數(shù)據(jù)庫性能的機(jī)會都沒有了。
喜歡的同學(xué)可以關(guān)注我的公眾號(db_arch)(Mysql數(shù)據(jù)庫運(yùn)維與架構(gòu)設(shè)計)