1. 调整Apache MPM模块配置
Apache的并发处理能力核心取决于**MPM(多处理模块)**的选择与配置。Ubuntu下需先禁用默认的mpm_prefork(适合静态内容、线程不安全场景),启用更高效的mpm_worker(多线程+进程混合模型)或mpm_event(事件驱动,优化长连接):
sudo a2dismod mpm_prefork # 关闭prefork
sudo a2enmod mpm_worker # 开启worker(或mpm_event)
sudo systemctl restart apache2
mpm_worker参数(以150并发为例):/etc/apache2/mods-enabled/mpm_worker.conf,调整以下参数:<IfModule mpm_worker_module>
StartServers 2 # 启动时的进程数
MinSpareThreads 25 # 最小空闲线程数
MaxSpareThreads 75 # 最大空闲线程数
ThreadsPerChild 25 # 每个进程的线程数
MaxRequestWorkers 150 # 最大并发请求数(=进程数×线程数)
MaxConnectionsPerChild 0 # 每个进程处理的请求数(0=无限制)
</IfModule>
注:mpm_event配置类似,但更适合长连接(如WebSocket),可将MaxConnectionsPerChild设为非零值(如1000)以避免内存泄漏。2. 优化系统资源限制
Apache的并发处理受限于系统的文件描述符和TCP连接限制,需调整以下参数:
/etc/security/limits.conf,添加:* soft nofile 65535
* hard nofile 65535
修改/etc/pam.d/login,添加:session required pam_limits.so
/etc/sysctl.conf,添加:net.ipv4.tcp_tw_reuse = 1 # 复用TIME-WAIT状态的连接
net.core.somaxconn = 4096 # 增加监听队列长度
生效配置:sudo sysctl -p
3. 启用缓存与压缩模块
减少重复请求和传输数据量,提升并发处理效率:
sudo a2enmod cache cache_disk
编辑/etc/apache2/mods-enabled/cache_disk.conf,配置缓存目录:<IfModule mod_cache_disk.c>
CacheRoot /var/cache/apache2/mod_cache_disk
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
</IfModule>
sudo a2enmod deflate expires
编辑/etc/apache2/mods-enabled/deflate.conf,添加压缩类型:<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
</IfModule>
4. 调整KeepAlive参数
允许客户端复用TCP连接,减少连接建立的开销(适用于HTTP/1.1):
编辑Apache主配置文件(/etc/apache2/apache2.conf),添加:
KeepAlive On # 开启KeepAlive
MaxKeepAliveRequests 100 # 单个连接最大请求数
KeepAliveTimeout 5 # 连接保持时间(秒)
5. 使用负载均衡与反向代理
通过分发请求到多个Apache实例,提升整体并发处理能力:
sudo a2enmod proxy proxy_balancer lbmethod_byrequests
/etc/apache2/sites-available/balancer.conf):<Proxy balancer://mycluster>
BalancerMember http://backend1.example.com loadfactor=3
BalancerMember http://backend2.example.com loadfactor=1
</Proxy>
ProxyPass / balancer://mycluster/
ProxyPassReverse / balancer://mycluster/
6. 监控与持续调优
使用工具监控性能,根据实际情况调整参数:
htop(查看CPU/内存使用)、netstat -tulnp(查看连接状态)、apachetop(查看请求速率)。ab(ApacheBench)模拟并发请求,评估优化效果:ab -n 1000 -c 100 http://your-server-ip/
注:-n表示总请求数,-c表示并发数。