遇到 ERROR 1040 (08004): Too many connections 時,通常是連接數超過 max_connections 限制。本文提供從診斷到優化的完整方案。
mysql> SHOW VARIABLES LIKE 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 100 |
+-----------------+-------+
mysql> SHOW GLOBAL STATUS LIKE 'Max_used_connections';
+----------------------+-------+
| Variable_name | Value |
+----------------------+-------+
| Max_used_connections | 5 |
+----------------------+-------+
Max_used_connections / max_connections × 100% ≈ 85% 為理想值
mysql> SET GLOBAL max_connections = 1500;
適用於緊急臨時調整,配合方案二永久生效。
# /etc/my.cnf
[mysqld]
max_connections = 1500
# 相關聯動參數建議同步調整
innodb_buffer_pool_size = 2G # 內存 60-70%
innodb_log_file_size = 256M
open_files_limit = 65535
table_open_cache = 4000
thread_cache_size = 100
service mysqld restart
finally 關閉邏輯# HikariCP 示例
maximumPoolSize = 20 # 每應用實例
minimumIdle = 5
connectionTimeout = 30000
idleTimeout = 600000
maxLifetime = 1800000
總連接數 ≈ 應用實例數 × maximumPoolSize,預留 20% 緩衝給管理連接。
mysql> SHOW PROCESSLIST;
# 關注 Time 列較大、State 為 Sending data/Locked 的查詢
優化慢 SQL、添加索引、限制大結果集分頁。
thread_cache_size 減少線程創建開銷# 關鍵指標監控
Threads_connected / max_connections > 80% → 告警
Threads_running / Threads_connected > 50% → 高負載告警
Aborted_connects 急增 → 應用連接異常
[mysqld]
# 連接數配置
max_connections = 2000
max_connect_errors = 100000
thread_cache_size = 200
back_log = 500
# 連接超時控制
wait_timeout = 28800 # 8小時
interactive_timeout = 28800
net_read_timeout = 30
net_write_timeout = 60
# 內存相關(按實際內存調整)
innodb_buffer_pool_size = 4G
key_buffer_size = 256M
tmp_table_size = 64M
max_heap_table_size = 64M