Openresty实现获取内部location

-- 三种方式实现获取内部location信息
--[[
location /api1 {
    echo_sleep 3;
    echo api1: $arg_a;
}
location /api2 {
    echo_sleep 3;
    echo api2: $arg_a;
}
]]

-- 串行实现
local t1 = ngx.now()
local res1 = ngx.location.capture("/api1", {args = ngx.req.get_uri_args()})
local res2 = ngx.location.capture("/api2", {args = ngx.req.get_uri_args()})
local t2 = ngx.now()
ngx.print(res1.body, "<br/>", res2.body, "<br/>", tostring(t2 - t1))


-- ngx.location.capture_multi实现
-- 直接使用ngx.location.capture_multi来实现,比如访问http://192.168.1.2/concurrency1?a=22
local t1 = ngx.now()
local res1, res2 = ngx.location.capture_multi(
{
    {"/api1", {args = ngx.req.get_uri_args()}},
    {"/api2", {args = ngx.req.get_uri_args()}}
})
local t2 = ngx.now()
ngx.print(res1.body, "<br/>", res2.body, "<br/>", tostring(t2 - t1))


-- 协程API
-- 使用ngx.thread.spawn创建一个轻量级线程,然后使用ngx.thread.wait等待该线程的执行成功。比如访问http://192.168.1.2/concurrency2?a=22
local t1 = ngx.now()
local function capture(uri, args)
    return ngx.location.capture(uri, args)
end
local thread1 = ngx.thread.spawn(capture, "/api1", {args = ngx.req.get_uri_args()})
local thread2 = ngx.thread.spawn(capture, "/api2", {args = ngx.req.get_uri_args()})
local ok1, res1 = ngx.thread.wait(thread1)
local ok2, res2 = ngx.thread.wait(thread2)
local t2 = ngx.now()
ngx.print(res1.body, "<br/>", res2.body, "<br/>", tostring(t2 - t1))
-- 我们可以通过下面的方式实现任意一个成功即返回,之前的是等待所有执行成功才返回。
local ok, res = ngx.thread.wait(thread1, thread2)

转载于:https://www.cnblogs.com/one-villager/p/9370636.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值