wrk, 一个简单的 http 压测工具

https://github.com/wg/wrk

命令简介

Usage: wrk <options> <url>
  Options:
    -c, --connections <N>  Connections to keep open
    -d, --duration    <T>  Duration of test
    -t, --threads     <N>  Number of threads to use

    -s, --script      <S>  Load Lua script file
    -H, --header      <H>  Add header to request
        --latency          Print latency statistics
        --timeout     <T>  Socket/request timeout
    -v, --version          Print version details

  Numeric arguments may include a SI unit (1k, 1M, 1G)
  Time arguments may include a time unit (2s, 2m, 2h)

最简单使用, get

wrk -c1 -t1 -d1s http://localhost:8080

一个连接, 一个线程, 压测时长一秒

如何压测post接口?

wrk -c1 -t1 -d1s http://localhost:8080/api/postTest -s post_test.lua

写法1:

wrk.method = "POST"
wrk.headers["Content-Type"] = "application/json"
wrk.body = '{"from":"123","to":"333","fromDate":"2023-01-16"}'

写法2:

-- lua多行字符串,处理复杂json
jsonData = [[
  {
    "from":"122",
    "to":"aaa"
  }
]]
wrk.method = "POST"
wrk.headers["Content-Type"] = "application/json"
wrk.body = jsonData

高级扩展功能

wrk -c1 -t1 -d1s http://localhost:8080 -s counter.lua

-- example dynamic request script which demonstrates changing
-- the request path and a header for each request
-------------------------------------------------------------
-- NOTE: each wrk thread has an independent Lua scripting
-- context and thus there will be one counter per thread

counter = 0

request = function()
   path = "/hello/name?name=" .. counter
   wrk.headers["User-Agent"] = counter
   counter = counter + 1
   wrk["counter"] = counter
   -- print(counter)
   return wrk.format(nil, path)
end

done = function(summary, latency, requests)
   -- done 方法和 其他 不再一个 thread env 下执行, 所以读取的 counter 还是初始化时的 0
   print(counter)
   print(wrk.thread)
   print(wrk["counter"])
   print(summary.requests)
end

参考

  1. https://www.cnblogs.com/quanxiaoha/p/10661650.html
  2. https://github.com/wg/wrk/blob/master/SCRIPTING
  3. 非常棒的介绍文章, 使用wrk一键式压测后台接口