利用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代理指定目录
- 访问Nginx发生SSL connection error的一种情况
- Nginx+Naxsi部署专业级Web应用防火墙
- CentOS 6.2实战部署Nginx+MySQL+PHP
- nginx中http核心模块的配置指令2
- nginx中http核心模块的配置指令3
- nginx中http核心模块的配置指令4
- nginx中http的fastcgi模块的配置指令1
- 负载均衡技术沙龙1期(关于咱的图片)
- 负载均衡沙龙活动第二期现场问答汇集
- Nginx 学习笔记(一)
- 流量引导:网络世界的负载均衡解密
- 流量引导:网络世界的负载均衡解密
- 网站502与504错误分析
- 艰难完成 nginx + puma 部署 rails 4的详细记录
- 把Lua编译进nginx步骤方法
- 浅谈sqlserver的负载均衡问题
- web 应用中常用的各种 cache详解
- Linux系统上配置Nginx+Ruby on Rails+MySQL超攻略