wrk 支持在三个不同的阶段执行 LuaJIT 脚本
每个 wrk 线程都有一个独立的脚本环境,因为独有独立的 Lua 虚拟机
setup、done 阶段在一个单独的环境中执行,不参与 running 阶段
官方文档:https://github.com/wg/wrk/blob/master/SCRIPTING
-- POST 请求,演示如何添加
-- HTTP method, body, header
wrk.method = "POST"
wrk.body = "foo=bar&baz=quux"
wrk.headers["Content-Type"] = "application/x-www-form-urlencoded"
wrk = {
scheme = "http",
host = "localhost",
port = nil,
method = "GET",
path = "/",
headers = {},
body = nil,
thread = <userdata>
}
返回所有可用服务器的地址信息
上面也说到有三个阶段,setup、running、done 阶段,他们分别都有一些内置函数
thread.addr - get or set the thread's server address,获取或设置服务器地址信息
thread:get(name) - get the value of a global in the thread's env,获取当前线程参数
thread:set(name, value) - set the value of a global in the thread's env,设置当前线程参数
thread:stop() - stop the thread,终止线程
wrk.format()
方法,动态创建请求response
回调方法的话,wrk 就不会解析 header 和 bodylatency.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
}
}
这个感觉不常用,用到再举栗子吧
-- example script that demonstrates use of setup() to pass
-- data to and from the threads
local counter = 1
local threads = {}
function setup(thread)
-- 给每个线程设置一个 id 参数
thread:set("id", counter)
-- 将线程添加到 table 中
table.insert(threads, thread)
counter = counter + 1
end
function init(args)
-- 初始化两个参数,每个线程都有独立的 requests、responses 参数
requests = 0
responses = 0
-- 打印线程被创建的消息,打印完后,线程正式启动运行
local msg = "thread %d created"
print(msg:format(id))
end
function request()
-- 每发起一次请求 +1
requests = requests + 1
return wrk.request()
end
function response(status, headers, body)
-- 每得到一次请求的响应 +1
responses = responses + 1
end
function done(summary, latency, requests)
-- 循环线程 table
for index, thread in ipairs(threads) do
local id = thread:get("id")
local requests = thread:get("requests")
local responses = thread:get("responses")
local msg = "thread %d made %d requests and got %d responses"
-- 打印每个线程发起了多少个请求,得到了多少次响应
print(msg:format(id, requests, responses))
end
end
wrk -d3s -c20 -t5 -s test.lua https://*****/get
创建了 5 个线程, 以及每个线程发起的请求数和得到的响应数都有打印出来
为防止被盗,只放图片