优化Apache并发连接的关键策略
Apache的MPM(Multi-Processing Module)决定了其处理并发请求的方式,高并发场景下需根据需求选择:
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
KeepAlive允许客户端复用TCP连接发送多个请求,减少连接建立/关闭的开销,但需平衡资源占用与性能:
KeepAlive On(默认关闭,高并发场景必须开启)。KeepAliveTimeout 3。MaxKeepAliveRequests 150。ulimit -n 65535;/etc/security/limits.conf,添加:* soft nofile 65535
* hard nofile 65535
/etc/sysctl.conf:net.core.somaxconn = 65535 # 监听队列最大长度
net.ipv4.tcp_max_syn_backlog = 65535 # SYN队列最大长度
net.ipv4.tcp_tw_reuse = 1 # 允许复用TIME_WAIT状态的连接
net.ipv4.tcp_fin_timeout = 30 # TIME_WAIT状态超时时间(秒)
运行sysctl -p使配置生效。通过缓存静态内容或动态响应,减少对后端服务器的请求,提升响应速度:
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
</IfModule>
</IfModule>
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"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
启用Gzip压缩,减小响应数据量,提升传输效率:
LoadModule deflate_module modules/mod_deflate.so
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
top、htop监控CPU、内存使用;netstat -antp查看连接数;ss -s查看TCP连接状态。access.log查看请求响应时间,error.log排查错误(如“Too many open files”)。ab)或JMeter模拟高并发,验证配置效果。示例:ab -n 10000 -c 1000 http://example.com/
(-n表示总请求数,-c表示并发数)Timeout 5。