wrk lua 脚本使用 - WinChua/blog GitHub Wiki

1. lua 语法简介:

  • 基本数据类型包括了8种:

    • boolean
    • string
    • number
    • nil
    • table: {ok="OK"}; t={}, t.ok="OK"
    • function
    • thread
    • userdata
  • 环境: 有一个全局环境 _ENV

> a = 42
> _ENV.a
42
  • 循环
> start, end, step = 0, 10, 1
> for i = start, end, step do print(i); end;
> i = 0
> while i < 10 do print(i); i = i + 1; end
> repeat i = i - 1; print(i) ; until i <= 0 
  • 分支
if i > 10 then print(i) elseif i > 5 then print(5) else print(i) end
  • 函数定义
function fib(n)
  prev, now = 0, 1
  i = 0
  while i < n do prev, now = now, prev + now; i = i + 1; end
  return prev
end
  • 包管理
> function dir(a) keys = ""; for k, _ in pairs(a) do keys = keys .. "," .. k; end print(keys) end
> dir(package)
,searchers,loadlib,loaded,path,config,cpath,searchpath,preload
> dir(package.loaded)
,package,table,bit32,os,math,_G,string,debug,utf8,coroutine,io
>

package.loaded记录了当前已经require的package名称; package.path以及package.cpath定义了当前lua执行require的时候, 需要搜索的路径, 如果名字相同, lua会优先在path找纯lua的库, 再在cpath中找c extend.

LUA_PATH: 是一个定义package.path的环境变量, 会完全覆盖package.path

搜索一个库: package.searchpath("cjson", package.path .. ";" .. package.cpath)

2. wrk中的lua脚本

2.1 涉及到的几个api

  • setup(thread): 每一个thread将会执行一次, 执行的环境是全局之外的一个环境
  • init(): 每一次thread setup完之后调用, 环境是thread 自带的环境; init中定义变量名的时候, 会给thread的环境写入一个变量名的key, 可以直接在request, reponse 中直接使用变量名
  • request() --> return http : 每次http请求调用搞一次
  • reponse(status, header, body): 每次成功收到回包调用一次
  • done(summary, lantency, requests): 压测结束的时候调用, 环境是全局的

2.2 thread userdata的几个api

  • thread.addr : 当前thread使用的ip:port地址
  • thread:set(name, value): 向thread的环境中写入name = value
  • thread:get(name): 从thread的环境中获得名为name的环境变量
  • thread:stop() : 结束当前thread

2.3 wrk package

可以在init, response, request中使用wrk.thread 获得当前运行该还是的thread

demo:

threads = {}
function dir(module)
    for k, v in pairs(module)
    do
        print(k, v)
    end
end

counter = {}

function setup(thread)
    table.insert(threads, thread)
end

function init()
    wrk.thread:set("d", counter)
end

function request()
    return wrk.request()
end

function response(status, headers, body)
    if d[status] == nil then d[status] = 1;
    else
        d[status] = d[status] + 1
    end
end

function done(summary, latency, requests)
    for i, thread in ipairs(threads)
    do
        for k, v in pairs(thread:get("d"))
        do
            print(i, k, v)
        end
    end
end