使用wrk进行压力测试

最近需要对新的服务进行压力测试。比较了ab和jemeter以及wrk。最终选择wrk来作为压力测试工具,可以把cpu压到100%。

官方源码: https://github.com/wg/wrk

安装

git clone https://github.com/wg/wrk

make

-- 拷贝wrk到bin
cp wrk /usr/sbin/wrk

使用

具体介绍参考: https://segmentfault.com/a/1190000014591330

这里主要用到一个简单的用法:指定线程数,连接数,压测时间,随机参数

单独固定测试一个接口

wrk -t100 -c1000 -d30s  --latency "http://192.168.58.57:9111/api/v1/location/point?thePointNum=3&lonLat=117.269552,26.299981"
使用方法: wrk <选项> <被测HTTP服务的URL>                            
  Options:                                            
    -c, --connections <N>  跟服务器建立并保持的TCP连接数量  
    -d, --duration    <T>  压测时间           
    -t, --threads     <N>  使用多少个线程进行压测   
                                                      
    -s, --script      <S>  指定Lua脚本路径       
    -H, --header      <H>  为每一个HTTP请求添加HTTP头      
        --latency          在压测结束后,打印延迟统计信息   
        --timeout     <T>  超时时间     
    -v, --version          打印正在使用的wrk的详细版本信息
                                                      
  <N>代表数字参数,支持国际单位 (1k, 1M, 1G)
  <T>代表时间参数,支持时间单位 (2s, 2m, 2h)

随机参数

指定请求req脚本即可。lua语法简单了解一下即可。

wrk -t100 -c1000 -d30s -s req.lua --latency "http://192.168.58.57:9111"

req.lua

request = function()
   local lg1 = math.random(103, 119)
   local lg2 = math.random(0, 999999)
   local lat1 = math.random(23, 40)
   local lat2 = math.random(0, 999999)
   local path = "/api/v1/location/point?thePointNum=3&lonLat=" .. lg1 .. "." .. lg2 .. "," .. lat1 .. "." .. lat2

   return wrk.format(nil, path)
end

--[[ 以下可以在简单测试的时候打印结果,验证,但若是性能测试,需要注释掉 ]]
response = function(status, headers, body)
  print(body)
end

wrk Post 接口测试

首先需要准备一个lua文件

wrk.method = "POST"
wrk.headers["Content-Type"] = "application/x-www-form-urlencoded"
wrk.body = "youbody&youset"
这个文件内容建议自己填写,保存为 post.lua 文件

当然这个脚本内容可以再次定义,具体查看wrk的git文档

执行脚本

wrk -t4 -c2000 -d60s -T5s --script=post.lua --latency http://192.168.31.107/user/login
这样就是模拟4个线程,2000个连接,在60s内,间隔5s 执行 post.lua 的请求

你可以扩展一下,制作 shell 脚本来批量测试各种接口
如测试post json:

post.lua
-- example HTTP POST script which demonstrates setting the
-- HTTP method, body, and adding a header
wrk.method = "POST"
wrk.body   = "{\"q\":1}"
wrk.headers["Content-Type"] = "application/json"
posted @ 2018-12-27 10:58  Ryan.Miao  阅读(3627)  评论(0编辑  收藏  举报