應用程式報錯 ERROR 1040 (HY000): Too many connections,且 MySQL 服務重啟時間異常漫長(數 GB 資料庫卻需數分鐘才能啟動完成)。
-- 登入 MySQL 後執行(立即生效,重啟失效)
SET GLOBAL max_connections = 1000;
SET GLOBAL wait_timeout = 600; -- 10 分鐘
-- 查看當前連線
SHOW PROCESSLIST;
-- 批量殺除 Sleep 狀態超過 60 秒的連線
SELECT CONCAT('KILL ', id, ';') FROM information_schema.PROCESSLIST
WHERE COMMAND = 'Sleep' AND TIME > 60 AND USER != 'system_user';
[mysqld]
# 連線設定
max_connections = 2000
wait_timeout = 600
interactive_timeout = 600
max_user_connections = 1500 -- 單用戶上限防止佔滿
# InnoDB 啟動優化
innodb_buffer_pool_size = 4G -- 實體記憶體 60-80%
innodb_log_file_size = 512M
innodb_log_files_in_group = 3
innodb_fast_shutdown = 1 -- 正常關機加速,重啟時需做恢復
innodb_flush_log_at_trx_commit = 2 -- 平衡效能與安全
# 避免啟動時檢查大量 MyISAM 表
myisam_recover_options = FORCE,BACKUP
# /etc/security/limits.conf
mysql soft nofile 65535
mysql hard nofile 65535
# systemd 服務檔
LimitNOFILE=65535
LimitNPROC=65535
// Node.js mysql2 範例
createPool({
connectionLimit: 50, -- 根據 max_connections 分配
acquireTimeout: 10000, -- 取得連線超時
idleTimeout: 300000, -- 閒置 5 分鐘回收
enableKeepAlive: true,
keepAliveInitialDelay: 10000
})
connection.release() 或 conn.end()# Prometheus + Grafana 關鍵指標
mysql_global_status_threads_connected / mysql_global_variables_max_connections > 0.8 → 告警
mysql_global_status_aborted_connects 快速上升 → 應用連線異常
mysql_global_status_slow_queries > 閾值 → 效能退化
"Too Many Connections" 多為配置不足與應用洩漏雙重作用。系統性解決需三管齊下:調大服務端上限、縮短閒置超時、修復應用連線池管理。啟動緩慢則需從硬體、引擎參數、資料庫架構三方面綜合優化。