wrk - 基于C的HTTP压力测试工具
——————————————————————————————————————————————
WARN:通篇皆为MacOS操作,WindowsOS/LinuxOS等需自行变更为同等操作。
——————————————————————————————————————————————
优点:
- 简单易用
- 单机高性能高并发
缺点:
- 仅支持单机
- 仅支持HTTP
- 仅支持简单场景
- 仅支持命令行模式
- 测试结果简单
安装
# 安装wrk
brew install wrk
# 检查
wrk -V
命令参数
wrk <选项> <被测HTTP服务的URL>
Options:
-c, --connections <N> 跟服务器建立并保持的TCP连接数量
-d, --duration <T> 压测时间
# threads一般设置为CPU核数的2-4倍
-t, --threads <N> 使用多少个线程进行压测,压测时,是有一个主线程来控制我们设置的n个子线程间调度
-s, --script <S> 指定Lua脚本路径
-H, --header <H> 为每一个HTTP请求添加HTTP头
--latency 在压测结束后,打印延迟统计信息
--timeout <T> 超时时间
-v, --version 打印正在使用的wrk的详细版本信
<N>代表数字参数,支持国际单位 (1k, 1M, 1G)
<T>代表时间参数,支持时间单位 (2s, 2m, 2h)
运行命令
# GET请求示例
wrk -t8 -c200 -d30s --latency http://www.bing.com
wrk -t20 -c300 -d60s --latency https://www.bing.com -H "authorization: xxx"
lua脚本
可访问变量
wrk = {
scheme = "http",
host = "localhost",
port = nil,
method = "GET",
path = "/",
headers = {},
body = nil,
thread = <userdata>,
}
可访问方法
# 根据参数和全局变量wrk,生成一个HTTP rquest string
function wrk.format(method, path, headers, body)
# 给定host和service(port/well known service name),返回所有可用的服务器地址信息
function wrk.lookup(host, service)
# 测试与给定的服务器地址信息是否可以成功创建连接
function wrk.connect(addr)
POST方法的lua脚本(string)
wrk.method = "POST"
wrk.headers["S-COOKIE2"]="a=2&b=Input&c=10.0&d=20191114***"
wrk.body = "recent_seven=20191127_32;20191128_111"
wrk.headers["Host"]="api.shouji.**.com"
function response(status,headers,body)
if status ~= 200 then --将服务器返回状态码不是200的请求结果打印出来
print(body)
-- wrk.thread:stop()
end
end
POST方法的lua脚本(string)
request = function()
local headers = { }
headers['Content-Type'] = "application/json"
body = {
mobile={"1533899828"},
params={code=math.random(1000,9999)}
}
local cjson = require("cjson")
body_str = cjson.encode(body)
return wrk.format('POST', nil, headers, body_str)
end
运行命令
wrk -t8 -c200 -d30s --latency -s test.lua http://www.bing.com
or
wrk -t10 -c200 --latency -s test.lua https://pre-gw.hntv.tv/api/article/detail/1602567955137617922 -H "authorization: xxx"
结果分析
Running 30s test @ http://www.bing.com (压测时间30s)
8 threads and 200 connections (共8个测试线程,200个连接)
Thread Stats Avg Stdev Max +/- Stdev
(平均值) (标准差)(最大值)(正负一个标准差所占比例)
Latency 46.67ms 215.38ms 1.67s 95.59%
(延迟)
Req/Sec 7.91k 1.15k 10.26k 70.77%
(处理中的请求数)
Latency Distribution (延迟分布)
50% 2.93ms
75% 3.78ms
90% 4.73ms
99% 1.35s (99分位的延迟:%99的请求在1.35s以内)
1790465 requests in 30.01s, 684.08MB read (30.01秒内共处理完成了1790465个请求,读取了684.08MB数据)
Requests/sec: 59658.29 (平均每秒处理完成59658.29个请求)
Transfer/sec: 22.79MB (平均每秒读取数据22.79MB)