1)使用ngx.location.capture
返回一个包含四个元素的 Lua 表 (res.status, res.header, res.body, 和 res.truncated)。
因为 Nginx 内核限制,子请求不允许类似 @foo 命名 location。请使用标准 location,并设置 internal 指令,仅服务内部请求。
有以下参数:
method, body, args, ctx, vars, copy_all_vars, share_all_vars, always_forward_body。
location /product {
internal;
echo "商品请求";
}
location /order {
content_by_lua_block {
ngx.req.read_body()
local args, err = ngx.req.get_post_args(100)
-- 返回 res.status, res.header, res.body, res.truncated
local res = ngx.location.capture("/product", {
method = ngx.HTTP_GET,
args = {a = args.a, b = args.b}
})
ngx.say(res.status)
ngx.say(res.body)
}
}
2)使用ngx.location.capture_multi
local res1, res2 = ngx.location.capture_multi({
{"/sum", {args={a=3, b=4}}},
{"/sub", {args={a=3, b=4}}}
})
ngx.say(res1.status, res1.body)
ngx.say(res2.status, res2.body)
res1, res2, res3 = ngx.location.capture_multi{
{ "/foo", { args = "a=3&b=4" } },
{ "/bar" },
{ "/baz", { method = ngx.HTTP_POST, body = "hello" } },
}
if res1.status == ngx.HTTP_OK then
end
if res2.body == "BLAH" then
end
local reqs = {}
table.insert(reqs, { "/mysql" })
table.insert(reqs, { "/postgres" })
table.insert(reqs, { "/redis" })
table.insert(reqs, { "/memcached" })
local resps = { ngx.location.capture_multi(reqs) }
for i, resp in ipairs(resps) do
-- process the response table "resp"
end