NGINX 结合 lua 动态修改upstream


from http://blog.csdn.net/force_eagle/article/details/51966333

 

具体思路是: 

1 > 利用lua中 "lua_shared_dict" 指令开辟一个共享内存空间;

2> 通过API动态根据key值&参数修改 upstream  (这里使用 host 作为key);

3> 利用 proxy_pass 可使用变量特性及lua指令 "set_by_lua" 动态修改当前 upstream 变量即可;

 

以下是利用 qq.com 作为示例:

 

[plain] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. http {  
  2.     lua_shared_dict _ups_zone 64m; # 定义upstream共享内存空间  
  3.     ...  
  4.     upstream qq_backend{  
  5.         server 14.17.42.40;  
  6.         server 14.17.32.211;  
  7.         server 59.37.96.63;  
  8.     }  
  9.   
  10.     server {  
  11.         listen       80;  
  12.         server_name  www.qq.com *.qq.com;  
  13.         access_log  off;  
  14.   
  15.         # 更新 upstream API 接口  
  16.         location = /ups_update {  
  17.             content_by_lua '  
  18.                 local ups = ngx.req.get_uri_args()["ups"]  
  19.                 if ups == nil then  
  20.                     ngx.say("usage: /ups_update?ups=x.x.x.x")  
  21.                     return  
  22.                 end  
  23.                 local host = ngx.var.http_host  
  24.                 local ups_from = ngx.shared._ups_zone:get(host);  
  25.                 ngx.log(ngx.WARN, host, " update upstream from ", ups_from, " to ", ups)  
  26.                 ngx.shared._ups_zone:set(host, ups);  
  27.                 ngx.say(host, " update upstream from ", ups_from, " to ", ups)  
  28.             ';  
  29.         }  
  30.         location / {  
  31.             # 动态设置当前 upstream, 未设置则使用默认 upstream  
  32.             set_by_lua $cur_ups '  
  33.                 local ups = ngx.shared._ups_zone:get(ngx.var.http_host)  
  34.                 if ups ~= nil then  
  35.                     ngx.log(ngx.ERR, "get [", ups, "] from ngx.shared._ups_zone")  
  36.                     return ups  
  37.                 end  
  38.                 --ngx.log(ngx.INFO, "use default upstream");  
  39.                 return "qq_backend";  
  40.             '  
  41.             proxy_next_upstream off;  
  42.             proxy_set_header    Host $host;  
  43.             proxy_http_version  1.1;  
  44.             proxy_set_header    Connection  "";  
  45.             proxy_pass $scheme://$cur_ups;  
  46.         }  
  47.     }  
  48. }  
 

 

[plain] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. cur -x 127.0.0.1:80 www.qq.com  # 使用默认upstream  
  2. # 修改为140.206.160.207 & 61.135.157.156  
  3. curl -x 127.0.0.1:80 www.qq.com/ups_update?ups=140.206.160.207  
  4. curl -x 127.0.0.1:80 www.qq.com/ups_update?ups=61.135.157.156  

 

这里只是一个简单的思路,并未考虑到 upstream 持久化,如需要可参考以下这篇文章, 使用 Redis 来实现:

Dynamic nginx upstreams with Lua and Redis 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM