mysql優化鏈接數防止訪問量太高的方法

不少開發人員都會碰見」MySQL: ERROR 1040: Too many connections」的異常狀況,形成這種狀況的一種緣由是訪問量太高,MySQL服務器抗不住,這個時候就要考慮增長從服務器分散讀壓力;另外一種緣由就是MySQL配置文件中max_connections值太小。

首先,咱們來查看mysql的最大鏈接數:
mysql

mysql>show variables like '%max_connections%';
+ -----------------+-------+
| Variable_name  | Value |
+ -----------------+-------+
| max_connections | 151  |
+ -----------------+-------+
1 row in set (0.00 sec)

其次,查看服務器響應的最大鏈接數:
sql

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服務器最大鏈接上限值設置太高。
Max_used_connections / max_connections * 100% = 2/151 *100% ≈ 1%
上面咱們知道怎麼查看mysql服務器的最大鏈接數值,而且知道了如何判斷該值是否合理,下面咱們就來介紹一下如何設置這個最大鏈接數值。
方法1:
服務器

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服務便可。
code


mysql>show variables like 'max_connections';(查能夠看當前的最大鏈接數)開發

msyql>set  global  max_connections=1000;(設置最大鏈接數爲1000,能夠再次查看是否設置成功)
相關文章
相關標籤/搜索