lyd2004888 发表于 2018-11-9 10:21:28

基于cookie在nginx实现业务灰度发布

  基于cookie在nginx实现业务灰度发布
  背景
  灰度发布是指在黑与白之间,能够平滑过渡的一种发布方式。
  灰度发布可以保证整体系统的稳定,
  在初始灰度的时候就可以发现、调整问题,以保证其影响度。
  业务存在灰度发布的需求,
  可以通过nginx+lua形式实现业务的灰度发布,
  目前这一形式已在广平互动广告相关业务已经实现。
  流程
  用户使用帐号登录后,判断用户帐号是否在灰度发布的名单中,如果再则给用户的cookie中增加灰度发布标识,然后刷新页面。
  当用户访问页面时,业务接入层的nginx方向代理会根据用户cookie是否带着灰度标识而对用户的请求进行选择,是转发到所有后端机器还是指定的灰度发布机器。
  方案
  业务维护一个用户帐号的灰度名单,在程序里面实现灰度帐号登录时cookie里面种相应的标识。
  用户请求发起时,nginx反向代理接入层通过获取请求中带的cookie的相关变量来判断当前请求是发往全量的服务器,还是发往灰度的服务器。
  灰度处理逻辑

  nginx接入层

  配置实例
  nginx配置静态页面的灰度规则
  server
  {
  listen 80;
  server_name test.qunyingliu.qq.com;
  access_log logs/test.qunyingliu.qq.com.access.log access;
  设置默认为全量发布
  set $group "Full";
  判断cookie中是否有灰度标识号
  if ($http_cookie ~* "FC_GREY=1"){
  set $group Grey;
  }
  location / {
  proxy_pass http://$group;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  index index.html index.htm;
  }
  }
  nginx配置PHP页面的灰度规则
  location @grey {
  proxy_next_upstream http_500 http_502 http_503 http_504 error timeout invalid_header;
  add_header ENV 'grey';
  proxy_pass http://Grey;
  }
  location @full {
  proxy_next_upstream http_500 http_502 http_503 http_504 error timeout invalid_header;
  add_header ENV 'full';
  proxy_pass http://FULL;
  }
  location ~ \.(php)?$ {
  content_by_lua_file "conf/lua/test.qunyingliu.qq.com.lua";
  }
  test.qunyingliu.qq.com.lua:
  local ck = require "resty.cookie"
  local grey_cookie_key = "FC_GREY"
  local cookie, err = ck:new()
  if not cookie then
  ngx.exec("@full")
  else
  local field, err = cookie:get(grey_cookie_key)
  if not field then
  ngx.exec("@full")
  else
  ngx.exec("@grey")
  end
  end
  灰度验证
  1.浏览器控制台设置灰度cookie
  console---> setCookie('FC_GREY',1)


  2.chrome扩展:EditThisCookie--->"+"---->添加新cookie

  3.业务里面给用户设置cookie
  总结
  需要业务端配合才能实现自动的灰度发布,
  主要规则是在nginx上使用lua脚本进行处理,
  请求的速度和稳定性可能会收到lua脚本处理的影响,
  界面普遍认为nginx+lua是非常好的搭配,
  相关开源方案OpenResty也是比较热门的,
  实际效果还需要在业务上线后进行验证。

页: [1]
查看完整版本: 基于cookie在nginx实现业务灰度发布