Nginx 实践 之 动态 upstream

发布于 2022-09-29 23:49:58 字数 1821 浏览 191 评论 0

nginx.conf

events {
  worker_connections 1024;
}

http {
  lua_package_path ';;$prefix/lua/?.lua;';

  server {
    listen 8111;
    location / {
      echo "8111:$request";
    }
  }
  server {
    listen 8112;
    location / {
      echo "8112:$request";
    }
  }

  upstream remote8111 {
    server 127.0.0.1:8111;
  }
  upstream remote8112 {
    server 127.0.0.1:8112;
  }

  server {
    listen 8110;

    location /test/debug {
      default_type 'text/html';
      charset utf-8;
      content_by_lua_file lua/hello.lua;
    }
    location /capture {
      content_by_lua_block {
        (require "lua.test").capture()
      }
    }
    location /exec {
      content_by_lua_block {
        (require "lua.test").exec()
      }
    }
    location /upstream {
      # 下面两行必须设置,否则会报告错误:nginx: [emerg] unknown "my_upstream" variable
      set $my_upstream $my_upstream;
      set $my_uri $my_uri;
      proxy_pass $my_upstream$my_uri;
    }
  }
}

lua/test.lua

local _M = {_VERSION = '1.0'}

local location_capture = ngx.location.capture
local ngx_var = ngx.var
local ngx_exec = ngx.exec
local ngx_HTTP_OK = ngx.HTTP_OK
local ngx_HTTP_GET = ngx.HTTP_GET

-- 输出响应内容体 (内容体结束后,再输出一个换行符).
local ngx_say = ngx.say
-- 输出响应内容体 (内容体结束后,不输出换行符).
local ngx_print = ngx.print

function _M:capture()
  local options = {
    method = ngx_HTTP_GET,
    vars = {
      my_upstream = 'http://remote8111',
      my_uri = '/hello'
    }
  }
  local res = location_capture('/upstream', options)
  if res and res.status == ngx_HTTP_OK then
    ngx_print(res.body)
    return
  end

  ngx_say('capture failed')
end

function _M:exec()
  ngx_var.my_upstream = 'http://remote8112'
  ngx_var.my_uri = '/world'
  ngx_exec('/upstream')
end

return _M

测试

run/openresty-1.13.6.2/nginx 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

飘然心甜

暂无简介

文章
评论
493 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文