首页  

Apache Bench (ab) 性能测试     所属分类 tech 浏览量 49
1. ab 工具简介
Apache Bench (ab) 是 Apache HTTP Server 附带的性能测试工具,
用于模拟多线程并发请求,测试 Web 服务器(如 Apache、Nginx、IIS 等)的负载能力

特点:
轻量级,对测试机资源占用低,但对目标服务器压力大 
适用于快速基准测试,但不适用于复杂场景(如动态参数、Cookie 等)
常用于简单 HTTP 接口、静态页面的压力测试 

2. 基本命令示例
(1) 简单并发测试

ab -n 1000 -c 100 http://example.com/
-n 1000:总请求数 1000 
-c 100:并发用户数 100 
目标 URL 可以是 IP 或 域名

(2) 限时测试

ab -t 60 -c 50 http://example.com/
-t 60:测试持续 60 秒 
-c 50:每秒 50 个并发请求 

(3) POST 请求测试(带 JSON 数据)

ab -n 1000 -c 100 -p data.json -T "application/json" http://example.com/api

-p data.json:POST 请求的 JSON 数据文件(需与 ab 同目录) 
-T "application/json":设置 Content-Type 为 application/json1 

3. 结果分析
执行测试后,ab 会输出如下关键指标:
plaintext
Server Software:        nginx/1.18.0
Server Hostname:        example.com
Server Port:            80

Document Path:          /
Document Length:        1024 bytes

Concurrency Level:      100
Time taken for tests:   2.345 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      1256000 bytes
HTML transferred:       1024000 bytes
Requests per second:    426.44 [#/sec] (mean)
Time per request:       234.500 [ms] (mean)
Time per request:       2.345 [ms] (mean, across all concurrent requests)
Transfer rate:          523.12 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   0.5      1       3
Processing:    45  230  50.2    245     400
Waiting:       10  150  40.1    160     300
Total:         45  231  50.3    246     403

Percentage of the requests served within a certain time (ms)
  50%    246
  66%    260
  75%    270
  80%    280
  90%    300
  95%    320
  98%    350
  99%    380
 100%    403 (longest request)


关键指标解读:
Requests per second:服务器每秒处理的请求数(QPS),越高越好 
Time per request (mean):单个请求的平均响应时间(单位:ms) 
Failed requests:失败请求数,若不为 0,需检查服务器或网络问题 
Connection Times:连接、处理、等待时间分布 
Percentage served within time:响应时间分布,如 90% 的请求在 300ms 内完成

4. 常见问题
(1) 测试结果不准确?
带宽限制:建议在内网测试,避免网络延迟影响 
服务器资源不足:若目标服务器 CPU/内存满载,测试结果可能失真 

(2) POST 请求如何传参?
使用 -p 指定数据文件,如:
ab -n 100 -c 10 -p postdata.txt -T "application/x-www-form-urlencoded" http://example.com/api
postdata.txt 内容示例:
username=test&password=123

(3) 如何模拟不同用户?
ab 本身不支持动态会话,如需更复杂测试(如 Cookie、Session),建议使用 JMeter 或 Locust 

5. 总结
ab 是一款简单易用的 HTTP 压测工具,适合快速评估服务器性能 
但对于复杂场景(如动态参数、登录态保持),建议使用更专业的工具(如 JMeter)

如果需要更详细的 AB 测试案例(如 Google、Facebook 的优化策略),可参考企业级 AB 测试实践

上一篇     下一篇
欧洲简史

王安石 与 司马光

spring线程池 ThreadPoolTaskExecutor 配置

《财富与周期:宏观经济第一课》笔记

MySQL8 JSON 使用

国际局势常用术语