使用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"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM