調整 max_connections 有「動態生效」與「配置持久化」兩條路徑,看似同歸殊途,實則在生效時效、持久性、運維風險上有本質差異。本文通過實測對比,給出場景化選擇指南。
mysql> SET GLOBAL max_connections = 100;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 100 |
+-----------------+-------+
ERROR 1227 (42000): Access denied; you need SUPER privilege(s)my.cnf 配置值Sleep 連接保留
# 終端 A 設置 max_connections=1
SET GLOBAL max_connections = 1;
# 終端 B 嘗試新連接
mysql -uroot -p
ERROR 1040 (HY000): Too many connections
# /etc/my.cnf
[mysqld]
max_connections = 100
# 重啟生效
/etc/init.d/mysqld restart
# 或 systemctl restart mysqld
| 維度 | SET GLOBAL (動態) | my.cnf (持久化) |
|---|---|---|
| 生效速度 | 毫秒級 | 重啟後(秒~分級) |
| 持久性 | 重啟失效 | 永久生效 |
| 業務影響 | 零中斷 | 需重啟,短暫不可用 |
| 權限要求 | SUPER | 系統 root/sudo |
| 配置漂移風險 | 高(運行態與文件態不一致) | 低(單一事實來源) |
| 適用場景 | 緊急擴容、臨時壓測、故障止血 | 容量規劃、版本發布、長期調優 |
SET GLOBAL max_connections = 新值 即時緩解my.cnf,避免重啟回滾SHOW VARIABLES 與 my.cnf 一致性max_connections × (sort_buffer + read_buffer + join_buffer + thread_stack) < 物理內存 70%maxPoolSize 必須 < MySQL max_connections,預留 10-20% 給管理連接
#!/bin/bash
# 用法: ./sync_max_connections.sh 2000
NEW_VAL=$1
CNF="/etc/my.cnf"
# 1. 動態生效
mysql -uroot -p${PASS} -e "SET GLOBAL max_connections = ${NEW_VAL};"
# 2. 更新配置文件
if grep -q "^max_connections" "$CNF"; then
sed -i "s/^max_connections.*/max_connections = ${NEW_VAL}/" "$CNF"
else
sed -i "/^\[mysqld\]/a max_connections = ${NEW_VAL}" "$CNF"
fi
# 3. 記錄審計
echo "[$(date)] max_connections changed to ${NEW_VAL} by $(whoami)" >> /var/log/mysql_config_changes.log
動態調整是「止血藥」,配置持久化是「根治方案」。成熟運維體系要求:每一次動態調整,必有對應的配置變更單。