預設 max_connections = 151 (5.1 前 100),高併發場景極易耗盡,導致新連線被拒、服務假死。
vi /usr/local/mysql/bin/mysqld_safe
# 找到兩處 $ledir/$MYSQLD 啟動行,尾部追加
-O max_connections=1500
# 具體位置 (紅字標示)
then
$NOHUP_NICENESS $ledir/$MYSQLD \
$defaults --basedir=$MY_BASEDIR_VERSION \
--datadir=$DATADIR $USER_OPTION \
--pid-file=$pid_file \
--skip-external-locking \
-O max_connections=1500 \
>> $err_log 2>&1
else
eval "$NOHUP_NICENESS $ledir/$MYSQLD \
$defaults --basedir=$MY_BASEDIR_VERSION \
--datadir=$DATADIR $USER_OPTION \
--pid-file=$pid_file \
--skip-external-locking $args \
-O max_connections=1500 \
>> $err_log 2>&1"
fi
重啟驗證:
service mysqld restart
mysqladmin -uroot -p variables | grep max_connections
# 輸出 max_connections 1500 即生效
# 解壓源碼包
cd mysql-5.0.33/sql
vi mysqld.cc
# 找到
{"max_connections", OPT_MAX_CONNECTIONS,
"The number of simultaneous clients allowed.",
(gptr*) &max_connections, (gptr*) &max_connections,
0, GET_ULONG, REQUIRED_ARG, 100, 1, 16384, 0, 1, 0},
# 將預設值 100 → 1500
{"max_connections", OPT_MAX_CONNECTIONS,
...
1500, 1, 16384, 0, 1, 0},
./configure && make && make install
# 重啟服務生效
# /etc/my.cnf 或 /usr/local/mysql/etc/my.cnf
[mysqld]
max_connections = 2000
# 伴隨參數建議同步調大
open_files_limit = 65535
table_open_cache = 4000
thread_cache_size = 100
back_log = 200
優勢:無需改腳本/源碼,版本升級保留,集中管理,SET GLOBAL max_connections=2000 可運行時動態調整 (不超過啟動值)。
-- 理論記憶體上限
max_connections * (sort_buffer_size + join_buffer_size + read_buffer_size + read_rnd_buffer_size)
+ global_buffers (innodb_buffer_pool_size, key_buffer_size, etc.)
-- 實際監控
SHOW STATUS LIKE 'Max_used_connections'; -- 歷史峰值
SHOW STATUS LIKE 'Threads_connected'; -- 當前連線數
SHOW PROCESSLIST; -- 詳細會話
建議:Max_used_connections / max_connections < 80% 為安全區;超過持續擴容或優化慢查詢釋放連線。
my.cnf 不重啟 → 不生效。mysqld_safe 但用 systemctl start mysqld (systemd 直接拉起 mysqld,繞過 mysqld_safe) → 不生效。open_files_limit、ulimit -n 系統限制 → 「Can't open file」錯誤。