對於中高用量的 MySQL 伺服器, 提高 max_connections 是必然的設定, 不然便會出現 too many connections 錯誤。但 max_connections 這個數值不可以任意提高的, 如果設定太高, 會出以類似以下的錯誤:
例如設定 max_connections 到 1000, 系統出現上面 Warning 後, max_connections 會停留在 214.
出現這個問題的原因, 是因為 MySQL 每開啟一個連線也會開啟一些檔案, 如果 MySQL 發現 open files limit (開啟檔案數量限制) 太小, 不足以應付 max_connections 的設定, 便會自動降低, 只要將這個數值設定高一點便可以, 以下是設定提高 MySQL 的 open files limit 的方法:
要提高 open files limit, 可以分別用設定系統的 ulimit 及 MySQL 參數兩個方法完成:
由於只想設定 MySQL 的 open files limit, 以下也只會針對 mysql 帳號 (MySQL 在系統的帳號) 的 open files limit 提高, 開啟檔案 /etc/security/limits.conf:
例如我想將 open files limit 提高到 10240, 加入以下兩行:
1 2 |
mysql hard nofile 10240 mysql soft nofile 10240 |
然後開啟 /lib/systemd/system/mysql.service:
在 [Service] 段落, 加入以下兩行:
1 2 |
LimitNOFILE = 10240 LimitMEMLOCK = 10240 |
然後重新載入啟動 MySQL, 由於改動了 /lib/systemd/system/mysql.service, 需要先執行 systemctl daemon-reload:
# systemctl restart mysql
想檢查 MySQL 的 open files limit 確認, 可以這樣, 先登入 MySQL:
執行以下指令:
1 |
mysql> show global variables like 'open%'; |
如果設定正確, 會看到以下內容:
1 2 3 4 5 6 |
+------------------+--------+ | Variable_name | Value | +------------------+--------+ | open_files_limit | 1024000 | +------------------+--------+ 1 row in set (0.00 sec) |
No Responses