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