《wrk Lua 脚本扩展压测》
1 简介
wrk 内置 LuaJIT 运行时,通过 -s script.lua 加载 Lua 脚本,可以在每个线程内自定义请求生成、响应处理与结束统计逻辑,满足动态参数、签名 header、随机 IP 等复杂压测场景。
2 基本用法
wrk -c 1000 -t 1000 -d 10 -s ip_info.lua 'http://127.0.0.1:8080'
提醒:并发数
-c与线程数-t一般根据被测服务配置,线程数远大于 CPU 核心数并不能线性提升吞吐。
3 Lua 脚本接口
每个线程初始化时调用一次:
init = function(args)
end
每个请求调用,返回 HTTP 报文:
request = function()
end
每个响应回调(可选):
response = function(status, headers, body)
end
压测结束时回调(可选):
done = function(summary, latency, requests)
end
4 示例:动态请求头 + 随机 IP
local wrk = wrk
local wrk_format = wrk.format
local str_format = string.format
local io_open = io.open
local random = math.random
local file = io_open("result.txt", "w+")
request = function ()
local method = "GET"
local headers = {}
headers["x-user-id"] = "123"
headers["x-id"] = "456"
headers["x-sign"] = "654321"
headers["host"] = "api.example.com"
local a = random(1, 250)
local b = random(1, 250)
local c = random(1, 250)
local d = random(1, 250)
local ip = str_format("%s.%s.%s.%s", a, b, c, d)
local path = str_format("/api/ip/info?type=base&ip=%s", ip)
return wrk_format(method, path, headers)
end
response = function (status, headers, body)
file:write(status)
file:write(body .. "\n")
end
done = function (summary, latency, requests)
file:close()
end
5 wrk.format 构造请求
wrk.format 根据参数与全局表 wrk 生成一个 HTTP 请求字符串:
function wrk.format(method, path, headers, body)
method:HTTP 方法,如 GET / POSTpath:URL 路径(含参数)headers:请求头body:请求体
6 done 回调的 summary 结构
summary = {
duration = N, -- 压测时长(微秒)
requests = N, -- 完成的总请求数
bytes = N, -- 收到的总字节数
errors = {
connect = N, -- socket 连接错误数
read = N, -- socket 读错误数
write = N, -- socket 写错误数
status = N, -- HTTP 状态码 > 399 的数量
timeout = N -- 请求超时数
}
}
7 wrk 全局属性
wrk = {
scheme = "http",
host = "localhost",
port = nil,
method = "GET",
path = "/",
headers = {},
body = nil,
thread = <userdata>,
}
8 wrk 的 Lua 接口
| 全局函数 | 说明 |
|---|---|
init(args) |
线程初始化时调用 |
request() |
每个请求返回 HTTP 报文 |
response(status, headers, body) |
收到响应数据后回调 |
done(summary, latency, requests) |
压测结束时回调 |
function wrk.format(method, path, headers, body)
-- 将传入参数与 wrk 表合并生成 HTTP 请求字符串
9 常见问题
9.1 压测机自身成为瓶颈
压测时 errors.timeout 与 errors.connect 大量出现,先检查压测机端口/连接是否耗尽,改用 -H "Connection: keep-alive" 或适当降低 -c。若非服务器问题,优先排查压机侧资源。
10 参考文档
阅读 —
·
全站 —