在工作中,大家或許常常遇到Too many connections這個錯誤,這時作為DBA想進數據庫管理都進不去,是非常尷尬的一件事情。當然有同學說可以修改配置文件,但是修改配置文件是需要重啟mysqld的,這在業務繁忙的數據庫服務器上是不允許的。所以緊急情況下可以采用如下的方法,比如下面的測試。
[root@mysql-server-01 msb_5_6_19]# ./use ERROR 1040 (HY000): Too many connections [root@mysql-server-01 msb_5_6_19]#
我上面是采用MySQL沙箱環境,關於沙箱環境的簡單安裝及使用請參看我前面的文章。MySQL Sandbox安裝使用
可以看見我上面已經報了錯誤,提示也非常明顯,就是我們配置的連接數太小,現在已經用完了,這時我們剛想進數據庫做些操作,那么采用如下方法:
[root@mysql-server-01 ~]# gdb -p $(cat /root/sandboxes/msb_5_6_19/data/mysql_sandbox5619.pid) -ex "set max_connections=500" -batch [New LWP 27541] [New LWP 27540] [New LWP 27539]
[Thread debugging using libthread_db enabled] 0x00000031152df343 in poll () from /lib64/libc.so.6 [root@mysql-server-01 ~]#
下面再次登錄數據庫看看,並查看最大連接數是否已經修改
[root@mysql-server-01 msb_5_6_19]# ./use Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 22 Server version: 5.6.19-log MySQL Community Server (GPL) Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql [localhost] {msandbox} ((none)) > show variables like 'max_connections'; +-----------------+-------+ | Variable_name | Value | +-----------------+-------+ | max_connections | 500 | +-----------------+-------+ 1 row in set (0.00 sec) mysql [localhost] {msandbox} ((none)) >
在Percona5.5的thread_pool里面提供了2個參數extra_port和extra_max_connections預留額外的連接,預防連接滿了以后我們無法進入數據庫進行相應的管理。
root@localhost : (none) 23:18:00> show variables like '%extra%'; +-----------------------+-------+ | Variable_name | Value | +-----------------------+-------+ | extra_max_connections | 1 | | extra_port | 10086 | +-----------------------+-------+ 2 rows in set (0.00 sec) root@localhost : (none) 23:18:04>
[root@mysql-server-01 user_3307]# netstat -nltp | grep 10086 tcp 0 0 0.0.0.0:10086 0.0.0.0:* LISTEN 29655/mysqld [root@mysql-server-01 user_3307]#
我這里使用了10086端口,以及最大連接數為1。有這么貼心的功能。必須給一個贊
總結:
通常控制最大連接數有兩個參數控制max_connections(該實例允許最大的連接數 ),max_user_connections(該實例允許每個用戶的最大連接數),通常情況下前期我們就需要規划好多少連接數合適。一般情況下建議不要超過300。因為MySQL在連接數上升的情況下性能下降非常厲害,如果需要大量連接,這時可以引入thread_pool。所以我們需要保持一個原則:系統創建的用戶(給應用使用用戶)數* max_user_connections < max_connections。這樣就不會發生文章開始說的問題。
參考資料
http://www.mysqlperformanceblog.com/2010/03/23/too-many-connections-no-problem/
http://www.percona.com/doc/percona-server/5.5/performance/threadpool.html
