預設 max_connections=100,高併發場景頻現 Too many connections。MySQL 5.0 手工編譯版 /etc/my.cnf 設定可能不生效,需從啟動腳本或原始碼入手。
vi /usr/local/mysql/bin/mysqld_safemysqld 啟動行(通常有兩處,對應不同條件分支),在參數末尾加入:-O max_connections=1500
具體位置範例:
# 第一處
$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"
/usr/local/mysql/bin/mysqld_safe & 或 service mysql restart。mysqladmin -u root -p variables | grep max_connections → 應顯示 1500。sql/mysqld.cc。max_connections 定義陣列:{"max_connections", OPT_MAX_CONNECTIONS,
"The number of simultaneous clients allowed.",
(gpointer) &max_connections, (gpointer) &max_connections,
0, GET_ULONG, REQUIRED_ARG, 100, 1, 16384, 0, 1},
100 改為 1500(第 8 個參數)。./configure --prefix=/usr/local/mysql ...(原配置參數)
make
make install
[mysqld]
max_connections = 1500
# 同步調大開啟檔案數限制
open_files_limit = 65535
若 my.cnf 不生效,檢查:
mysqld --help --verbose | grep -A1 'Default options'ulimit -n 限制(需在 /etc/security/limits.conf 設定 mysql 用戶)。| 參數 | 建議值 | 說明 |
|---|---|---|
| max_connections | 1500~3000 | 視記憶體與併發峰值 |
| thread_cache_size | 100~200 | 減少線程創建開銷 |
| back_log | 500~1000 | 連接請求隊列長度 |
| open_files_limit | 65535 | 系統層面開檔數上限 |
| innodb_buffer_pool_size | 物理記憶體 60~70% | 核心效能參數 |
SHOW VARIABLES LIKE 'max_connections';
SHOW STATUS LIKE 'Threads_connected';
SHOW STATUS LIKE 'Max_used_connections';
-- Max_used_connections / max_connections > 85% 考慮擴容
掌握三種修改路徑,靈活應對不同部署模式下的連接數擴容需求。