利用openresty-lua生态修改upstream后端服务

http{
  lua_shared_dict _G 1m;  # ngx多进程全局共享内存,保存upstream值
  ......
  upstream default_upstream {
     server unix:/var/run/app-1.sock;
     server 127.0.0.0.:38888;
     keepalive 24;
  }
  ......
  server{
      location = /_switch_upstream {
        content_by_lua '
            local ups = ngx.req.get_uri_args()["upstream"]       
            if ups == nil then
               ngx.say("usage: curl /_switch_upstream?upstream=unix:/path-to-sock-file")
               return
            end
            local host = ngx.var.http_host
            local ups_src = ngx.shared._G:get(host)
            ngx.log(ngx.WARN, host, " change upstream from ", ups_src, " to ", ups)
            ngx.shared._G:set(host,  ups)
            ngx.say(host, " change upstream from ", ups_src, " to ", ups)
        ';   

      }

      location ~ (^/api/|^/p/|^/m/|^/oauthapi/) {
        set_by_lua $my_upstream '
          local ups = ngx.shared._G:get(ngx.var.http_host)
          if ups ~= nil then
             ngx.log(ngx.ERR, "get [", ups,"] from ngx.shared")
             return ups
          end
          return "default_upstream"
        ';

        proxy_next_upstream off;
        proxy_set_header    X-Real-IP           $remote_addr;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        proxy_set_header    Host                $host;
        proxy_http_version  1.1;
        proxy_set_header    Connection  "";
        proxy_pass          http://$my_upstream ;
    }
  }
}

需要切换后端upstream时,使用命令:

curl http://127.0.0.1/_switch_upstream?upstream=unix:/path-to-sock-file
可以直接换成本地socket文件,也可以是ip:port, 也可是配置中预设了别一个upstream名。

关于 liuzhantao

北京互联网求职群:168047123
此条目发表在 lua, nginx, openresty 分类目录。将固定链接加入收藏夹。