不少開發人員都會碰見」MySQL: ERROR 1040: Too many connections」的異常狀況,形成這種狀況的一種緣由是訪問量太高,MySQL服務器抗不住,這個時候就要考慮增長從服務器分散讀壓力;另一種緣由就是MySQL配置文件中max_connections值太小。node
首先,咱們來查看mysql的最大鏈接數:mysql
?sql
1服務器 2測試 3spa 4.net 5code 6htm 7ci |
mysql> show variables like '%max_connections%' ; + -----------------+-------+ | Variable_name | Value | + -----------------+-------+ | max_connections | 151 | + -----------------+-------+ 1 row in set (0.00 sec) |
其次,查看服務器響應的最大鏈接數:
?
1 2 3 4 5 6 7 |
mysql> show global status like 'Max_used_connections' ; + ----------------------+-------+ | Variable_name | Value | + ----------------------+-------+ | Max_used_connections | 2 | + ----------------------+-------+ 1 row in set (0.00 sec) |
能夠看到服務器響應的最大鏈接數爲2,遠遠低於mysql服務器容許的最大鏈接數值。
對於mysql服務器最大鏈接數值的設置範圍比較理想的是:服務器響應的最大鏈接數值佔服務器上限鏈接數值的比例值在10%以上,若是在10%如下,說明mysql服務器最大鏈接上限值設置太高。
?
1 |
Max_used_connections / max_connections * 100% = 2/151 *100% ≈ 1% |
咱們能夠看到佔比遠低於10%(由於這是本地測試服務器,結果值沒有太大的參考意義,你們能夠根據實際狀況設置鏈接數的上限值)。
再來看一下本身 linode VPS 如今(時間:2013-11-13 23:40:11)的結果值:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
mysql> show variables like '%max_connections%' ; + -----------------+-------+ | Variable_name | Value | + -----------------+-------+ | max_connections | 151 | + -----------------+-------+ 1 row in set (0.19 sec) mysql> show global status like 'Max_used_connections' ; + ----------------------+-------+ | Variable_name | Value | + ----------------------+-------+ | Max_used_connections | 44 | + ----------------------+-------+ 1 row in set (0.17 sec) |
這裏的最大鏈接數占上限鏈接數的30%左右。
上面咱們知道怎麼查看mysql服務器的最大鏈接數值,而且知道了如何判斷該值是否合理,下面咱們就來介紹一下如何設置這個最大鏈接數值。
方法1:
?
1 2 3 4 5 6 7 8 9 |
mysql> set GLOBAL max_connections=256; Query OK, 0 rows affected (0.00 sec) mysql> show variables like '%max_connections%' ; + -----------------+-------+ | Variable_name | Value | + -----------------+-------+ | max_connections | 256 | + -----------------+-------+ 1 row in set (0.00 sec) |
方法2:
修改mysql配置文件my.cnf,在[mysqld]段中添加或修改max_connections值:
max_connections=128 重啓mysql服務便可。