基础功
可参照: https://www.jianshu.com/p/5bc2b48bd695
栗子
HTTP_prot = {
{
method="get",
url="/api/live/health"
},
{
method="get",
url="/api/course/health"
}
}
respError = 0 --变量,用于记录错误请求的数量
local threads = {}
-- 启动阶段 (每个线程执行一次)
function setup(thread)
--thread:set("id", counter)
-- print("=========启动阶段==========")
table.insert(threads, thread)
-- print("setup->threads",threads[1].addr)
print("setup",thread.addr)
-- counter = counter + 1
end
--每个线程执行一次
init = function()
local r = {}
wrk.headers["Authorization"]= "按照实际情况填写"
-- 键从1 开始 非 0
for i, v in ipairs(HTTP_prot) do
path = v.url
method = string.upper(v.method)
--数组:可修改
r[i] = wrk.format(method, path)
end
--表:不可修改 将传递给request 阶段
req = table.concat(r)
-- print("遍历req table")
-- for k,v in ipairs(r) do
-- print(k,v)
-- end
end
--每个请求执行一次在请求开始之前
request = function()
return req --发送
end
--测试结果,每个链接返回都会执行一次
response = function(status, headers, body)
--判断返回结果是否正确,如果返回结果错误则打印返回结果,进入LOG.txt文件
if(not string.find(body,'"status":200')) then
respError = respError + 1
--以附加的方式打开只写文件
file = io.open("LOG.txt","a")
--写入文件
file:write(body.."\n")
--写入文件
file:flush()
end
end
-- 测试最终结果,在测试结束执行
done = function(summary, latency, requests)
local x4 = 0
for index, thread in ipairs(threads) do
x4 = x4 + thread:get("respError")
end
--执行时间,单位-秒
local durations = summary.duration / 1000000
--http status(状态)不是200,300开头的
local errors = summary.errors.status
--总的请求数
local requests = summary.requests
--有效请求数 = 总的请求数 - 错误请求数
local valid = requests - x4
local connect = summary.errors.connect
local read1 = summary.errors.read
local write1 = summary.errors.write
local timeout = summary.errors.timeout
local errorRate = string.format("%.1f",x4/requests*100)
io.write("+++++++++++++++压测结果+++++++++++++++\n")
io.write(" 测试持续时间: "..string.format("%.2f",durations).."s".."\n")
io.write(" 平均响应时间: "..string.format("%.2f",latency.mean / 1000).."ms".."\n")
io.write(" 最小响应时间: "..(latency.min / 1000).."ms".."\n")
io.write(" 最大响应时间: "..(latency.max / 1000).."ms".."\n")
io.write(" 全部请求数量: "..summary.requests.."\n")
io.write(" 错误请求数量: "..x4.."\n")
io.write(" 有效请求数量: "..valid.."\n" )
io.write(" 错误率: "..errorRate.."%\n")
io.write(" 每秒查询率: "..string.format("%.2f",valid / durations).."\n" )
io.write("+++++++++++++++++++++++++++++++++++++\n")
end
测试结果
wrk -t 1 -c 2 -d 3 https://xxx.yyy.com -s test.lua
Running 3s test @ https://xxx.yyy.com
1 threads and 2 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 61.89ms 6.12ms 76.74ms 58.51%
Req/Sec 58.00 14.78 80.00 79.31%
172 requests in 3.06s, 112.37KB read
Requests/sec: 56.28
Transfer/sec: 36.77KB
+++++++++++++++压测结果+++++++++++++++
测试持续时间: 3.06s
平均响应时间: 61.89ms
最小响应时间: 63.559ms
最大响应时间: 76.74ms
全部请求数量: 172
错误请求数量: 0
有效请求数量: 172
错误率: 0.0%
每秒查询率: 56.28
+++++++++++++++++++++++++++++++++++++