基礎功
可參照: 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
+++++++++++++++++++++++++++++++++++++