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

本文介绍了如何利用openresty的lua生态动态修改upstream,实现后端服务的动态负载均衡控制、平滑上下线及服务升级。通过配置代码和简单命令,可以轻松切换后端upstream服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

0.动态upstream的好处

openresty作者,最近也要开源(在我编写此文章时还没开源)他们已经使用的balancer-by-lua 特性,进展issues。能动态修改upstream,使用反向代理proxy_pass, 对后端进程或机器进行:

  • 动态的负载均衡控制;
  • 平滑上下线服务,升级服务;
  • 高可能保证–自动踢离线服务下线;

1.先说原理

想法参考自<http://sosedoff.com/2012/06/11/dynamic-nginx-upstreams-with-lua-and-redis.html>。此文章的做法是写进redis中,好处是能多机同时切换,不足是论询redis太频繁。基于openresty,使用lua的控制一个内存中的一个多进程全局变量(ngx.shard),按需地变改proxy_pass的目标upsteam。

2 直接上配置代码

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 ;
    }
  }
}

3.用法

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值