0%

压测工具Wrk使用

  以前一说到http的压力测试工具,多数人会说 ab、webbench、siege。 但这些工具不管是性能还是复杂度已经不能满足我们的需求了。 用wrk只是为了更好的获取吞吐。

1.WRK安装

  Mac brew install mac
  Linux https://github.com/wg/wrk.git && cd wrk && make

2. Wrk参数

输入wrk –help
  -c, –connections 需要模拟的连接数
  -d, –duration 测试时间
  -t, –threads 使用线程数量
  -s, –script 加载lua脚本
   -H, –header http头
  –latency 显示延迟统计
  –timeout 超时

3. Wrk测试

3. Wrk lua介绍

  不使用脚本wrk仅支持简单http get请求, 如需POST/PUT/DELETE请求需要写Lua脚本, 使用Lua脚本可以控制每次请求header/body等。

1
2
3
wrk.method = "POST"
wrk.headers["Content-Type"] = "application/json"
wrk.body = "{"a":100, "b":200}"

wrk -t4 -c2000 -d60s -T5s –script=post.lua –latency http://baidu.com
上面简单Lua脚本时间wrk使用POST请求,header中Content-Type=application/json, body内容为{“a”:100, “b”:200}
wrk lua脚本函数说明:

1
2
3
4
5
setup 线程出事后支持会调用一次   
init 每次请求发送之前被调用。可以接受 wrk 命令行的额外参数
delay 执行当前请求后,delay,执行下个请求
request 请求信息, 可以设置 方法/请求头/body信息
response 请求结果,可以统计请求信息,输出结果等

function setup(thread)

1
2
3
4
5
-- thread提供了1个属性,3个方法
-- thread.addr 设置请求需要打到的ip
-- thread:get(name) 获取线程全局变量
-- thread:set(name, value) 设置线程全局变量
-- thread:stop() 终止线程

function init(args)

1
2
3
4
-- 每个线程仅调用1次,args 用于获取命令行中传入的参数, 例如 --env=pre
function init(args)
-- do something
end

function request()

1
2
3
4
-- 每个线程调用多次,返回http请求
function request()
-- do something
end

function response(status, headers, body)
– do something
end

1
2
3
4
-- 每个线程调用多次,返回http响应
function response(status, headers, body)
-- do something
end

function delay()

1
2
3
4
-- 每个线程调用多次,发送下一个请求之前的延迟, 单位为ms
function delay()
-- do something
end

function done(summary, latency, requests)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
--可以用于自定义结果报表,整个过程中只执行一次
--[[latency.min -- minimum value seen
latency.max -- maximum value seen
latency.mean -- average value seen
latency.stdev -- standard deviation
latency:percentile(99.0) -- 99th percentile value
latency(i) -- raw value and count
summary = {
duration = N, -- run duration in microseconds
requests = N, -- total completed requests
bytes = N, -- total bytes received
errors = {
connect = N, -- total socket connection errors
read = N, -- total socket read errors
write = N, -- total socket write errors
status = N, -- total HTTP status codes > 399
timeout = N -- total request timeouts
}
}]]
function done(summary, latency, requests)
-- do something
end

3. Wrk lua例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bodyArray = {
`{"a":100, "b":1000}`,
`{"a":200, "b":2000}`,
`{"a":300, "b":3000}`
}

request = function()
wrk.method = "POST"
wrk.body = bodyArray[math.random(1, #bodyArray)]
wrk.headers["Content-Type"] = "application/json"
return wrk.format()
end

function response(status, headers, body)
print(body)
end

./wrk -t 4 -c 100 -d 30s –latency –timeout 1s -s test.lua http://baidu.com
使用上面lua脚本可以使用POST请求, 并且随机选择body中json信息, 输出response信息