您当前的位置:首页 > 计算机 > 服务器 > Nginx

Nginx 实践 之 动态 upstream

时间:12-14来源:作者:点击数:
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
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐