分享

nginx lua 实现ip和cookies纬度的AB-Test灰度发布

 贾朋亮博客 2014-11-20

背景说明

ab-test请参考百度百科的解释,对互联网从业者来说,这个非常熟悉。我最近在一个项目里折腾lua,顺便实现了常用的两种灰度方案。

安装与配置

安装

我们不把时间浪费在安装编译,这里直接使用已经将nginx,lua组合在一起的openresty,安装过程请参考官方Install指南。

配置

为了方便策略选择和切换,我们把2个纬度的配置分别放在不同的文件里,具体使用哪个策略,在域名的主配置中启用即可。

  • ip_gray.lua
     --添加ip后无需重启nginx,但删除ip需要reload生效
     local ip_config = ngx.shared.config;
     ClienIP=ngx.req.get_headers()["X-Real-IP"]
     if ClientIP == nil then
         ClientIP = ngx.req.get_headers()["x_forworded_for"]
     end
     if ClientIP == nil then
         ClientIP = ngx.var.remote_addr
     end
    -- ip列表配置放在nginx/conf目录下
     for line in io.lines("../conf/iplist.txt") do
         if not ip_config:get(line) then
              ip_config:set(line, "0")
         end
     end
     if ip_config:get(ClientIP) == "0" then
         ngx.exec("@gray_env")
     else
         ngx.exec("@product_env")
     end
  • cookies_gray.lua
    local uin = ngx.var.cookie_loginuin
    --取cookies里的loginuin字段,末尾被2整数的灰度
    if uin ~= nil and string.sub(uin,string.len(uin))%2 == 0 then
      ngx.exec("@gray_env")
    else
      ngx.exec("@product_env")
    end
    
  • nginx.conf
      ...
      #http
      lua_code_cache off; #正式上线记得打开cache
      lua_package_path "/usr/local/openresty/lualib/?.lua;;";
      lua_shared_dict config 1m;
      ...
      #server
      location / {
         #access_by_lua_file  conf/lua/ip_gray.lua;
         access_by_lua_file  conf/lua/cookies_gray.lua;
      }
      location @gray_env {
          proxy_pass http://gray_env;
          proxy_set_header Host $http_host;
      }
      location @product_env {
          proxy_pass http://product_env;
          proxy_set_header Host $http_host;
      }
    

总结

  1. nginx打开debug日志,方便查看错误提示和调试信息
  2. lua语法不熟练时,首先翻阅官方文档,google搜索其次。因为google到的资料很可能是过期的,而且很多是没验证过的转帖。
  3. 合理使用共享内存

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多