【问题标题】:How do I issue an http request after proxy pass? Using openresty (lua + nginx)代理通过后如何发出http请求?使用 openresty (lua + nginx)
【发布时间】:2018-01-31 09:18:59
【问题描述】:

我也有类似的需求https://github.com/openresty/lua-nginx-module/issues/220

我的用例

  1. 我正在通过使用proxy_pass 将文件转发到远程服务器。
  2. 代理通过后,我需要将$body_bytes_sent 传递给远程网址。
  3. 我想过做一个content_by_lua 块,将ngx.capture 转发到proxy_pass 块,ngx.say() 返回来自ngx.capture 的内容。随后是一个带有 $body_bytes_sent 的请求到远程 url。但我需要支持流式传输,这是不行的。而且文件可能会变得很大,这对ngx.capture() 不利。
  4. 我想过做一个log_by_lua 块,但是cosockets apis 被禁用了。 https://github.com/openresty/lua-nginx-module#log_by_lua

【问题讨论】:

  • 不要觉得这有点矫枉过正,我们会做类似的事情,即跟踪请求信息,但是,您可以使用 beats 来搜索这些信息并在 NGINX 中定义日志文件。也许将其发布到 logstash 实例
  • 包含proxy_pass 的块有一个查询微服务的access_by_lua 块。在我们的设置中,微服务接收来自 log_by_lua 的数据,它可以确定是否应该访问特定的 url。 ----proxy_pass里面的远程服务器不受我们控制。所以我们不可能在那里完成。 --- 对 Logstash 进行了一些思考。但我认为这会使事情变得复杂,因为我需要将日志副本发送到微服务。
  • 您是否发现“不会阻止 nginx 工作人员”通过 http 发送数据的东西?
  • 很遗憾没有。还是有阻塞操作。

标签: nginx lua openresty


【解决方案1】:

安装 Lua-Curl 或其他不依赖 cosockets 的库。 (https://github.com/Lua-cURL/Lua-cURLv3)

如果你使用的是 luarocks(openresty 自带),请安装

apt-get install libcurl3 libcurl3-gnutls libcurl4-openssl-dev --yes

luarocks install Lua-cURL

像这样使用log_by_lua(例如log_by_lua_block、log_by_lua_file)。

# some nginx conf

location /a_location_with_proxy_pass {
    proxy_pass https://example.com:443;
    log_by_lua_file /path/to/luafile.lua;
}

你的 log_by_lua_file 然后应该向远程服务器发出 curl 请求。

local cURL = require 'curl'

curlHandle = cURL.easy{
    url        = 'https://remote_host.com/endpoint',
    post       = true,
    httpheader = {
        'Content-Type: application/json';
    },
    postfields = '{"bytes":' .. ngx.var.body_bytes_sent .. '}'
};
curlHandle:perform();

【讨论】:

  • 这里的坏事是你会阻塞 nginx worker 直到收到响应。
  • 恐怕是这样。我更喜欢proxy_passngx.capture - 因为我正在处理文件。但这意味着,我只能在 log_by_lua 中获得 $body_bytes_sent,它不允许使用 cosockets。我更喜欢不会阻止 nginx 工作人员但找不到其他任何东西的东西。如果您还有其他任何事情,即使只是想法,也很想听听! :D
猜你喜欢
  • 1970-01-01
  • 2018-08-25
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 2020-10-31
  • 2015-09-28
  • 1970-01-01
  • 2020-01-27
相关资源
最近更新 更多