ab 基准测试

基础用法

# 安装 # macOS: brew install httpd # Debian/Ubuntu: sudo apt install apache2-utils # CentOS/RHEL: sudo yum install httpd-tools ab -n 1000 -c 10 https://example.com/ # -n 总请求数 # -c 并发数(并行用户数) # -t 运行时间(秒),替代 -n ab -n 500 -c 5 http://localhost:3000/api/health ab -n 5000 -c 100 https://api.example.com/users ab -t 30 -c 50 http://localhost:8080/

POST 请求与请求头

# POST JSON 请求体(先创建 body 文件) # echo '{"username":"test","password":"pass"}' > body.json ab -n 500 -c 10 \ -p body.json \ -T application/json \ http://localhost:3000/api/login # 自定义请求头 ab -n 1000 -c 10 \ -H "Authorization: Bearer mytoken123" \ -H "Accept: application/json" \ http://localhost:3000/api/users # 携带 Cookie ab -n 500 -c 10 \ -C "sessionid=abc123" \ http://localhost:3000/dashboard

KeepAlive 与 HTTP 版本

# 启用 HTTP KeepAlive(持久连接) ab -n 5000 -c 100 -k http://localhost:3000/ # 每个请求超时(秒) ab -n 1000 -c 50 -s 30 http://localhost:3000/api/heavy # 详细输出 ab -n 100 -c 5 -v 2 http://localhost:3000/

结果导出

# 导出 gnuplot 数据文件 ab -n 5000 -c 50 -g results.tsv http://localhost:3000/ # 导出为 HTML 报告 ab -n 5000 -c 50 -w http://localhost:3000/ > report.html # 输出到文件 ab -n 1000 -c 20 http://localhost:3000/ | tee ab-results.txt

结果解读

Requests per second: 405.04 [#/sec] ← 吞吐量 Time per request: 123.45 [ms] ← 平均响应时间 Failed requests: 0 ← 0 为最佳 # 响应时间百分位(ms) 50% 116 ← 中位数(P50) 90% 162 ← P90 95% 180 ← P95 99% 215 ← P99 100% 460 ← 最慢请求

参数速查表

参数说明示例
-n总请求数-n 1000
-c并发数-c 50
-t运行时间(秒)-t 30
-k启用 KeepAlive-k
-pPOST 请求体文件-p body.json
-TContent-Type-T application/json
-H额外请求头-H "Auth: Bearer token"
-CCookie-C "sid=abc"
-g导出 gnuplot 数据-g out.tsv