您的位置:首页 > 编程语言 > Lua

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

2015-11-04 10:01 483 查看

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名。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  负载均衡 nginx