MySQL 預設 max_connections = 151 (5.7+) 或 100 (舊版),含 1 個 SUPER 保留連線。實際可用 = max_connections - 1。耗盡報錯:ERROR 1040 (HY000): Too many connections。
# 編輯 my.cnf / my.ini
[mysqld]
max_connections = 1000
# 同步調整關聯參數 (關鍵!)
open_files_limit = 100000
table_open_cache = 2000
thread_cache_size = 100
back_log = 3000
# 重啟生效
systemctl restart mysqld
mysql -u root -p
SET GLOBAL max_connections = 200;
SHOW VARIABLES LIKE 'max_connections';
SHOW GLOBAL STATUS LIKE 'Max_used_connections';
-- 必須同步更新配置檔,否則重啟失效
vi /usr/local/mysql/bin/mysqld_safe
# 找到 mysqld 啟動行,兩處均加入
-O max_connections=1500
# 範例:
$NOHUP_NICENESS $ledir/$MYSQLD $defaults ... -O max_connections=1500 >> $err_log 2>&1
eval "$NOHUP_NICENESS $ledir/$MYSQLD $defaults ... -O max_connections=1500 >> $err_log 2>&1"
service mysqld restart
mysqladmin -u root -p variables | grep max_connections
修改 sql/mysqld.cc 預設值 100→1500,重新 ./configure && make && make install。升級覆蓋、版本管理困難、編譯耗時。
| 參數 | 建議值 | 關係 |
|---|---|---|
open_files_limit |
max_connections × 5 + 10000 | OS 檔案描述符上限,含表、日誌、socket |
table_open_cache |
max_connections × 2 | 表快取,避免頻繁開關表 |
thread_cache_size |
min(100, max_connections/10) | 執行緒快取,減少建立/銷毀開銷 |
back_log |
min(3000, max_connections × 1.5) | TCP 連線佇列,應對突發連線風暴 |
innodb_buffer_pool_size |
依記憶體規劃 | 更多連線帶來更多查詢,需足夠緩衝池 |
# /etc/security/limits.conf
mysql soft nofile 65535
mysql hard nofile 65535
root soft nofile 65535
root hard nofile 65535
# /etc/sysctl.conf
fs.file-max = 1000000
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
sysctl -p
預估峰值併發連線 × 1.5~2max_connections - 10Threads_connected / max_connections > 80% 持續 → 擴容sort_buffer_size + join_buffer_size + read_buffer_size + thread_stack),1000 連線 ≈ 2-10GBmax_connections (全域) vs max_user_connections (單用戶,預設 0 無限制)科學規劃 max_connections 需結合:配置檔永久化 + 關聯參數同步 + OS 限制突破 + 監控告警 + 應用連線池合理配置 + 定期壓測驗證。單一參數調整非銀彈,系統性容量規劃才是穩定之道。