目录

如何使用 apache benchmark 对 API 进行压力测试

目录

在开发 API 完成后,测试的环节中免不了要进行压力测试。postman 的 runner 只支持串行化测试,不支持并发。jmeter 需要在本机上安装 JDK,且需要配置好 JAVA 环境变量,安装略显复杂,软件界面对小白并不友好,非开箱即用的工具。权衡之后,我个人推荐任何对压力测试毫无经验的人优先选择使用 Linux 环境下的 ab(apache benchmark)压测工具进行压力测试。

# 安装 ab
yum -y install httpd-tools

# 显示可选的参数列表及说明
ab -help
# 测试 
# c:并发数量
# n:总计请求数量
ab -c 100 -n 10000 https://yourdomain.com/getUserInfo?id=36&token=6vPgUT0gG1RyzBRKxYsSNBgwFwM1mQLz

耐心等待测试完毕,以下是测试报告

Server Software: nginx
Server Hostname: yourdomain.com
Server Port: 443
SSL/TLS Protocol: TLSv1.2,ECDHE-RSA-AES128-GCM-SHA256,2048,128
 
Document Path: getUserInfo?id=36&token=6vPgUT0gG1RyzBRKxYsSNBgwFwM1mQLz
Document Length: 41 bytes
 
Concurrency Level: 200
Time taken for tests: 187.546 seconds
Complete requests: 30000
Failed requests: 53
(Connect: 0, Receive: 0, Length: 53, Exceptions: 0)
Write errors: 0
Non-2xx responses: 47
Total transferred: 11695535 bytes
HTML transferred: 1235123 bytes
Requests per second: 159.96 [#/sec] (mean)
Time per request: 1250.304 [ms] (mean)
Time per request: 6.252 [ms] (mean, across all concurrent requests)
Transfer rate: 60.90 [Kbytes/sec] received
 
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 420 1078.0 286 63684
Processing: 50 640 996.0 609 69848
Waiting: 50 625 248.5 608 1796
Total: 217 1060 1452.9 951 69848
 
Percentage of the requests served within a certain time (ms)
50% 951 # 50%的请求在951ms内返回
66% 1074
75% 1152
80% 1205
90% 1391 # 90%的请求在1391ms内返回
95% 1660
98% 2043
99% 2928 # 99%的请求在2928ms内返回
100% 69848 (longest request)

比较重要的也就是最后这部分的 percent line 了,jmeter 只有 90%、95%、99% 这三个量级,ab 从 50% 到 100% 都有。