預設 max_connections=100 在並發場景下極易耗盡,導致「Too many connections」。本文提供兩種永久生效方案。
mysqld_safe (推薦,無需重編譯)vi /usr/local/mysql/bin/mysqld_safe
找到兩處 $ledir/$MYSQLD 啟動命令 (約第 400、420 行),在 --skip-external-locking 後追加:
-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"
保存後重啟驗證:
service mysqld restart
/usr/local/mysql/bin/mysqladmin -uroot -p variables | grep max_connections
# 輸出 max_connections 1500 即成功
cd /path/to/mysql-5.0.33/sql
vi mysqld.cc
搜尋 max_connections 定義處:
{"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},
將第 8 個參數 (默認值) 100 → 1500:
{"max_connections", OPT_MAX_CONNECTIONS,
"The number of simultaneous clients allowed.",
(gptr*) &max_connections, (gptr*) &max_connections,
0, GET_ULONG, REQUIRED_ARG, 1500, 1, 16384, 0, 1},
重新編譯安裝:
./configure [你的原參數]
make && make install
[mysqld]
max_connections = 1500
open_files_limit = 65535
table_open_cache = 1024
thread_cache_size = 100
back_log = 200
同步執行 ulimit -n 65535 並寫入 /etc/security/limits.conf。
SHOW VARIABLES LIKE 'max_connections';
SHOW GLOBAL STATUS LIKE 'Max_used_connections';
-- 觀察峰值佔比,長期 > 80% 需再擴容或治理洩漏
mysqld_safe 修改屬「運行時注入」,升級 MySQL 版本會失效,適合快速上線;源碼修改屬「編譯期固化」,適合構建企業標準鏡像。無論哪種,**配套參數同步調優** 才是穩定運行的前提。