OpenResty中的子查询,


Nginx 子请求是一种非常强有力的方式,它可以发起非阻塞的内部请求访问目标 location。目标 location 可以是配置文件中其他文件目录,或任何其他 nginx C 模块,需要注意的是,子请求只是模拟 HTTP 接口的形式,没有额外的 HTTP/TCP 流量,也没有IPC (进程间通信) 调用。所有工作在内部高效地在 C 语言级别完成。

原型:

local res = ngx.location.capture(uri)

返回一个包含四个元素的 Lua 表 (res.status,res.header,res.body, 和res.truncated)。

res.status(状态) 保存子请求的响应状态码。

res.header(头) 用一个标准 Lua 表储子请求响应的所有头信息。如果是“多值”响应头,这些值将使用 Lua (数组) 表顺序存储。

res.body(体) 保存子请求的响应体数据,它可能被截断。用户需要检测res.truncated(截断) 布尔值标记来判断

模拟get请求

local res = ngx.location.capture(

        '/foo?a=1',

        { args = { b = 3, c = 'a' } }

)

等同于

local res = ngx.location.capture('/foo?a=1&b=3&c=a')

foo.lua代码:

ngx.say("par_1=", ngx.var.b)

ngx.say("par_2=", ngx.var.c)

--do  some things ...

模拟post请求

do.lua代码:

local res = ngx.location.capture(

         '/bar',

         { 

                 method = ngx.HTTP_POST,

                 body = 'hello, world'

         }

)

bar.lua代码:

--do  some things ...

模拟post请求发送json字符串

easy.lua代码:

local res_userinfo = ngx.location.capture(

          '/dd',

          {

                 method = ngx.HTTP_POST,

                 body = cjson.encode( {

                            time   = 'time' ,

                            appid = 'appid' ,

                            sid     = 'sid' ,

                            from  = 'from' ,                                                    

                           page  = 'page'

                      })

          }

)

dd.lua代码:

ngx.req.read_body()

local json_str = ngx.req.get_body_data()

local arr      = comm:json_decode(json_str)

ngx.say(arr['sid'])

--do  some things ...

ngx.location.capture_multi用法差不多

local  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

...

相关内容

    暂无相关文章