Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Apache httpd 效能測試與調校實戰:ps/ab/ab -k、MPM 參數、KeepAlive、MaxClients 實測比較

編輯:系統常見問題解答

Apache 效能調校核心在於MPM 參數與記憶體使用平衡。以 Red Hat 系 httpd 2.4 (event MPM) 為例,完整測試流程:

1. 確認單進程記憶體佔用 (RSS)

ps -ylC httpd --sort:rss
# 輸出關鍵欄位:RSS (常駐記憶體 KB)、VSZ (虛擬記憶體 KB)
# 經驗值:event MPM 單進程 RSS 約 20~40 MB (含共享庫)
# 保守估算:可用記憶體 × 0.6 / 單進程 RSS = MaxRequestWorkers 上限

2. 基準測試工具:ab (ApacheBench)

# 1000 請求、100 併發、啟用 Keep-Alive
ab -n 1000 -c 100 -k https://example.com/

# 關鍵指標:
# Requests per second (RPS)
# Time per request (mean, across all concurrent)
# Transfer rate (KB/sec)
# Percentage of requests served within XX ms (P50/P90/P99)

3. 參數調整與重測循環

參數 (httpd.conf / conf.d/mpm.conf)預設值建議調整方向影響
ServerLimit256依記憶體上限設定 (≤ MaxRequestWorkers / ThreadsPerChild)進程數上限
MaxRequestWorkers256 (event: ServerLimit × ThreadsPerChild)≈ (可用 RAM × 0.6) / 單進程 RSS最大併發連線數
ThreadsPerChild2525~64 (依 CPU 核心、鎖競爭調整)每進程執行緒數
KeepAliveOnOn連線重用
KeepAliveTimeout5 (秒)2~3 秒 (高併發環境)釋放閒置連線速度
MaxKeepAliveRequests100100~500單連線最大請求數
AsyncRequestWorkerFactor21.5~3 (event MPM 專用)非同步工作者額外容量係數

4. 實測比較範例 (記憶體 4GB、保留 1.5GB 給 OS/DB)

# 方案 A:保守 (預設)
ServerLimit 16
MaxRequestWorkers 400
ThreadsPerChild 25
KeepAliveTimeout 5
→ ab -n 1000 -c 100 -k : RPS 1,200, P99 850ms, 平均負載 0.30

# 方案 B:激進
ServerLimit 32
MaxRequestWorkers 800
ThreadsPerChild 25
KeepAliveTimeout 2
→ ab -n 1000 -c 100 -k : RPS 2,100, P99 420ms, 平均負載 0.85 (接近飽和)

# 方案 C:平衡 (推薦)
ServerLimit 24
MaxRequestWorkers 600
ThreadsPerChild 25
KeepAliveTimeout 2
MaxKeepAliveRequests 200
→ ab -n 1000 -c 100 -k : RPS 1,850, P99 510ms, 平均負載 0.55

5. 進階調校

  • EnableMMAP Off、EnableSendfile On (核心 2.4+ 預設開啟,NFS 掛載需關閉)。
  • HostnameLookups Off (避免反向 DNS 查詢延遲)。
  • ExtendedStatus Off (關閉 mod_status 詳細統計,省 CPU)。
  • 模組精簡:LoadModule 僅保留必要 (mod_ssl, mod_proxy, mod_headers, mod_rewrite, mod_deflate, mod_expires, mod_security)。
  • 壓縮:mod_deflate + mod_brotli (httpd 2.4.26+)。
  • 快取:mod_cache_disk / mod_cache_socache + Redis/ Memcached 後端。

6. 持續驗證

  • 每次調整後跑 ab / wrk / h2load 至少 3 次取中位數。
  • 監控 top -bn1 | grep httpd、free -h、iostat -x 1、sar -n DEV 1。
  • 生產環境導入 Prometheus + node_exporter + apache_exporter 持續觀測 RPS、延遲分位、錯誤率、連線池使用率。

以資料驅動調校,而非經驗猜測,才能榨乾 Apache 效能。

Copyright © Windows教程網 All Rights Reserved