Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker 诊断工具


OpenResty 中使用 ngx.location.capture 完成第三方接口请求

OpenResty Lua 大约 1059 字

方法介绍

OpenResty自带方法,同步但非阻塞的Nginx子请求,模拟HTTP但没有额外的HTTP/TCP流量和IPC调用。

文档地址:https://github.com/openresty/lua-nginx-module#ngxlocationcapture

特别注意

  • 不能使用location @name配置方式;
  • 使用internal指令限制只能内部方法;
  • body参数只能使用string(可结合cjson完成application/json请求);
  • gzip后的请求不能被Lua正常解析,关闭转发header,设置proxy_pass_request_headersoff
  • ngx.timer中不能使用;

快速入门

此处只介绍作为HTTP客户端请求第三方接口的情况,用于内部之请求的情况,请查阅官方文档

Nginx配置

location = /api {
    internal;
    set_by_lua $target 'return ngx.ctx.target_uri';
    proxy_pass_request_headers off;
    proxy_pass $target;
}

GET请求

使用ngx.encode_args对参数进行urlencode

local args = {
    page = 1,
    size = 20
}

local res = ngx.location.capture('/api', {
    method = ngx.HTTP_GET,
    ctx = {
        target_uri = "http://127.0.0.1?" .. ngx.encode_args(args),
    }
})

POST请求

application/json示例

local req_param = json.encode({
    postId = 304
})
local res = ngx.location.capture('/api', {
    method = ngx.HTTP_POST,
    body = req_param,
    ctx = {
        target_uri = "http://127.0.0.1/post/random",
    }
})

开源案例

https://github.com/fendoudebb/z-blog-openresty

阅读 8530 · 发布于 2020-03-02

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批