MySQL 连接池与连接数调优实践
合理配置连接池和连接数可避免资源耗尽,提升应用性能。
1. 查看当前连接状态
SHOW STATUS LIKE 'Threads_connected';
SHOW STATUS LIKE 'Max_used_connections';
SHOW VARIABLES LIKE 'max_connections';2. max_connections 计算方法
根据应用服务器数量和连接池大小估算:
- 公式:
max_connections = (应用实例数 × 连接池大小) + 冗余20% - 例如:3台应用,每台4实例,每实例连接池50:
3×4×50 = 600,冗余后约 720。
3. 连接池参数建议(以 Druid 为例)
# 最大活跃连接数
maxActive=50
# 最小空闲连接
minIdle=5
# 获取连接超时时间(ms)
maxWait=60000
# 连接空闲超时回收
minEvictableIdleTimeMillis=3000004. 解决 Too many connections
-- 临时调大
SET GLOBAL max_connections = 1000;
-- 查看并 kill 空闲连接
SHOW PROCESSLIST;
KILL connection_id;5. 监控与预警
- 监控
Max_used_connections/max_connections比率,超过 80% 需扩容。 - 使用
performance_schema或第三方工具监控连接数。
合理的连接池配置是数据库稳定运行的关键。
