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)
相關文章
相關標籤/搜索