优化Apache并发连接数的关键步骤
Apache的多处理模块(MPM)直接决定并发处理模式,需根据场景选择:
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 10000
</IfModule>
注意:event模块需Apache 2.4+版本,且需禁用
KeepAlive或配合MaxKeepAliveRequests使用。
MaxClients):控制同时处理的最大请求数,需根据服务器内存计算。公式:MaxRequestWorkers = (总内存 - 系统预留内存) / 单个进程内存占用MaxRequestWorkers ≈ (8192 - 100)/50 ≈ 160。MaxRequestWorkers的1/4~1/3(如MaxRequestWorkers=150,StartServers=40)。Min/MaxSpareThreads):控制空闲进程/线程的最小/最大数量,避免频繁创建/销毁资源。建议MinSpareServers占MaxRequestWorkers的1/5,MaxSpareServers不超过MaxRequestWorkers的1/2。KeepAlive允许客户端复用TCP连接发送多个请求,减少连接建立/关闭的开销(HTTP请求响应时间可降低30%~50%)。配置示例如下:
KeepAlive On
MaxKeepAliveRequests 100 # 单个连接最大请求数(避免单个连接占用过久)
KeepAliveTimeout 5 # 连接保持超时时间(秒,建议5~10)
注意:高并发场景下,若
KeepAliveTimeout过长,会导致空闲连接占用资源,需平衡性能与资源消耗。
/etc/security/limits.conf,添加:* soft nofile 65535
* hard nofile 65535
编辑/etc/pam.d/common-session和/etc/pam.d/common-session-noninteractive,添加:session required pam_limits.so
重启服务器生效。/etc/sysctl.conf,添加以下参数提升网络性能:net.core.somaxconn = 65535 # 监听队列最大长度(避免连接被拒绝)
net.ipv4.tcp_max_syn_backlog = 65535 # SYN队列最大长度
net.ipv4.ip_local_port_range = 1024 65535 # 客户端可用端口范围
net.ipv4.tcp_tw_reuse = 1 # 复用TIME_WAIT连接
net.ipv4.tcp_fin_timeout = 30 # TIME_WAIT连接超时时间(秒)
执行sysctl -p使配置生效。使用缓存模块(如mod_cache、mod_expires)缓存静态资源(图片、CSS、JS),减少对后端服务器的请求,提升响应速度。配置示例如下:
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
LoadModule expires_module modules/mod_expires.so
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
</IfModule>
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
</IfModule>
</IfModule>
使用工具监控服务器性能,根据实际情况调整参数:
top(查看CPU/内存使用率)、htop(更直观的资源监控)、netstat -antp(查看连接状态,如ESTABLISHED、TIME_WAIT数量)。ab(Apache Benchmark)或siege模拟高并发请求,评估配置效果。例如:ab -n 10000 -c 1000 http://yourdomain.com/
其中-n表示总请求数,-c表示并发数。根据测试结果调整MaxRequestWorkers、KeepAliveTimeout等参数。mod_deflate压缩文本资源(HTML、CSS、JS),减少网络传输量。配置示例如下:LoadModule deflate_module modules/mod_deflate.so
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json