Lua 环境

直接上 openresty 镜像:image: openresty/openresty

需关注的是 openresty 的 nginx 路径在 /usr/local/openresty/nginx,如果有相对路径的配置,需要映射到这个路径下面。

脚本逻辑

模拟业务接口 /bizCenter/api/invoke 响应 业务ID 和 traceID。

参考示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
location /bizCenter/api/invoke {
content_by_lua_block {
-- 随机序列扩展
local file = io.open("/dev/urandom", "rb")
local bytes = file:read(4)
file:close()
local seed = 0
for i = 1, #bytes do
seed = 256 * seed + string.byte(bytes, i)
end
math.randomseed(seed)

-- 开始处理响应结果
local date = os.date("%y%m%d")
-- 业务数据生成
local randomNumber = math.random(100000000, 999999999)
local bizId = "330101" .. date .. randomNumber
-- traceId 生成 方法
local function random_char()
local x = math.random(0, 2)
if x == 0 then
-- 数字
return string.char(math.random(48, 57))
elseif x == 1 then
-- 大写字母
return string.char(math.random(65, 90))
else
-- 小写字母
return string.char(math.random(97, 122))
end
end
-- 请求 traceId
local traceId = ""
for i = 1, 32 do
traceId = traceId .. random_char()
end
-- 随机延迟几秒钟 按需模拟后端响应
-- local delay = math.random(1, 5)
-- os.execute("sleep " .. delay)
-- content-type 设置
ngx.header.content_type = 'application/json'
-- content-data 响应数据处理
ngx.say(string.format('{"resultStatus":"S", "data":"%s", "requestId":"%s", "resultCode":"1", "resultMsg":"%s"}', bizId, traceId, traceId))
}
}

生成 json 格式结果如:

1
2
3
4
5
6
7
{
"resultStatus": "S",
"data": "330101230610866090997",
"requestId": "got8A5wrW6oB2147v77CrA367Tjlf4mU",
"resultCode": "1",
"resultMsg": "got8A5wrW6oB2147v77CrA367Tjlf4mU"
}