性能测试工具 wrk 进阶学习
在上一次的学习中,我们了解了 wrk 的安装与简单使用,这次将进一步深入,体验 wrk 的实战应用。
我设置了几个接口用于测试,如下所示:
接口用途如下:
/test/hello:GET 请求测试
/test/post:简单的 POST 表单请求测试
/test/file:文件上传测试
1. GET 请求测试
首先进行 GET 请求。通过命令行查找本机的 IPv4 地址为 10.129.164.197
,项目运行在 8080
端口上。因此,针对 /test/hello
接口的 GET 请求命令如下:
wrk -t 5 -c 10 -d 10s --latency "http://10.129.164.197:8080/test/hello"
测试结果显示,总共发出了 193,981 个请求,项目控制台的日志记录也与此大致一致。
2. 带表单项的 POST 请求测试
对于 POST 请求的表单项传递需求,可以通过 Lua 脚本来实现更复杂的请求逻辑。官方提供了参考示例:
我编写了以下 Lua 脚本 post.lua
,以包含表单项内容:
wrk.method = "POST"
wrk.body = "str1=nx&int1=1"
wrk.headers["Content-Type"] = "application/x-www-form-urlencoded"
在 wrk 中使用 Lua 脚本时,需添加 -s
参数指定脚本文件:
wrk -t 5 -c 10 -d 10s -s post.lua --latency "http://10.129.164.197:8080/test/post"
测试结果显示,成功发送了 100,359 个请求,仅有 9 个超时。控制台日志显示接口成功处理了我们发送的内容。
3. 文件上传请求测试
文件上传请求原理上与 POST 请求类似,但 Lua 脚本需要构造 multipart/form-data
格式。以下是文件上传的 Lua 脚本内容:
-- 读取文件内容
local file = io.open("post.lua", "rb")
local file_content = file:read("*all")
file:close()
-- 构建 multipart/form-data 请求体
local boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
local body = "--" .. boundary .. "\r\n"
body = body .. 'Content-Disposition: form-data; name="file"; filename="post.lua"\r\n'
body = body .. "Content-Type: text/plain\r\n\r\n"
body = body .. file_content .. "\r\n"
body = body .. "--" .. boundary .. "--\r\n"
wrk.method = "POST"
wrk.body = body
wrk.headers["Content-Type"] = "multipart/form-data; boundary=" .. boundary
wrk.headers["Content-Length"] = tostring(#wrk.body)
使用以下命令发送文件请求:
wrk -t 5 -c 10 -d 10s -s file.lua --latency "http://10.129.164.197:8080/test/file"
结果显示文件请求成功发送,控制台记录的请求数量和超时数量与 wrk 输出基本一致,文件内容正确传输至接口。
总结
在这篇文章中,我们深入体验了 wrk 的应用,包括 GET 请求、带表单的 POST 请求以及文件上传请求的测试,进一步理解了 wrk 的灵活性与扩展性。
希望这篇分享能为你带来启发!如果你有任何问题或建议,欢迎在评论区留言,与我共同交流探讨。
License:
CC BY 4.0