優化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