
确保系统已安装 apache2-utils(包含 ab 工具):
sudo apt update sudo apt install apache2-utils -y
ab [选项] <URL>
选项 | 说明 | 示例值 |
| 总请求数 |
|
| 并发用户数 |
|
| 测试时长(秒) |
|
| 启用 HTTP Keep-Alive |
|
| 添加自定义请求头 |
|
| 指定 POST 数据文件 |
|
| POST 数据内容类型 |
|
测试 http://example.com/,模拟 100 个并发用户,共发起 1000 个请求:
ab -n 1000 -c 100 http://example.com/
启用 HTTP Keep-Alive(复用 TCP 连接,减少握手开销):
ab -n 1000 -c 100 -k http://example.com/
测试 POST 接口,需准备数据文件(如 postdata.txt):
# postdata.txt 内容示例:
{"username": "test", "password": "123456"}
# 执行测试:
ab -n 500 -c 50 -p postdata.txt -T "application/json" http://example.com/api/login
测试持续 60 秒,自动计算总请求数
ab -t 60 -c 100 http://example.com/
模拟浏览器请求或传递认证信息:
bash ab -n 1000 -c 100 -H "Authorization: Bearer token123" -H "User-Agent: MyTest" http://example.com/
将结果保存到文件以便分析:
bash ab -n 1000 -c 100 http://example.com/ > ab_report.txt
tee 实时查看并保存bash ab -n 1000 -c 100 http://example.com/ | tee ab_report.txt
Concurrency Level: 100 Time taken for tests: 5.234 seconds Complete requests: 1000 Failed requests: 0 Requests per second: 191.06 [#/sec] (mean) Time per request: 523.432 [ms] (mean) Time per request: 5.234 [ms] (mean, across all concurrent requests) Transfer rate: 123.45 [Kbytes/sec] received
htop、nmon 或 vmstat 监控服务器资源(CPU、内存、IO)。bash htop # 实时查看系统资源
-c)不宜过高,避免压垮服务器(建议从低并发逐步增加)。-n)需足够大以获取稳定数据(通常 ≥1000)。ab 默认支持 HTTPS,但若证书无效需添加 -k 忽略验证(不推荐生产环境使用):bash ab -k -n 1000 -c 100 https://example.com/