【openresty】蓝绿发布(ip白名单)

• 什么是蓝绿发布?

1. 蓝绿部署原理上很简单,就是通过冗余来解决问题。通常生产环境需要两组配置(蓝绿配置),一组是active的生产环境的配置(绿配置),一组是inactive的配置(蓝配置)。
2. 当用户访问的时候,只会让用户访问在绿色环境(active)的服务器集群。在绿色环境(active)运行当前生产环境中的应用,也就是旧版本应用version1。当你想要升级到version2 ,在蓝色环境(inactive)中进行操作,即部署新版本应用,并进行测试。如果测试没问题,就可以把负载均衡器/反向代理/路由指向蓝色环境了。
3. 随后需要监测新版本应用,也就是version2 是否有故障和异常。如果运行良好,就可以删除version1 使用的资源。如果运行出现了问题,可以通过负载均衡器指向快速回滚到绿色环境。

• openresty+redis实现api接口简单的蓝绿发布:

1. 当用户在发起请求后,判断用户当前的ip网络,如果发现是属ip白名单列表,则指向蓝色环境;若不在ip白名单列表,则指向绿色环境。
2. 下面以"订单中心接口"进行蓝绿发布,当请求匹配到`location /order_center`后,进过`gary_release.lua`文件处理,`gary_release.lua`文件会获取该请求的用户ip 和 redis中的ip白名单列表进行匹配,如果匹配成功会重新请求`location /gray_develop`这时候就会走蓝色环境,否则就会走绿色环境
 

《【openresty】蓝绿发布(ip白名单)》

【nginx.conf配置文件如下】:

http{
    upstream develop {
        server develop.banchengyun.com;
    }

    upstream online {
        server api.banchengyun.com;
    }

server{

    #灰度发布
    location /order_center {
        lua_code_cache off;
        default_type text/html;
        content_by_lua_file $root/gary_release.lua;
    }

    location /gray_develop {
        proxy_pass http://develop/bee/WW_verify_…;
    }

    location /gray_online {
        proxy_pass http://online/;
    }

}
}

【gary_release.lua文件如下】:
local redis = require(“resty.redis”);

— 创建一个redis对象实例。在失败,返回nil和描述错误的字符串的情况下
local redis_instance = redis:new();

–设置后续操作的超时(以毫秒为单位)保护,包括connect方法
redis_instance:set_timeout(10000)

–建立连接
local ip = ‘127.0.0.1’
local port = 6379
–尝试连接到redis服务器正在侦听的远程主机和端口
local ok,err = redis_instance:connect(ip,port)
if not ok then
        ngx.say(“connect redis error : “,err)
        return err
end

–获取请求ip
local local_ip = ngx.req.get_headers()[“X-Real-IP”];
if local_ip == nil then
   local_ip = ngx.req.get_headers()[“x_forwarded_for”];
end
if local_ip == nil then
   local_ip = ngx.var.remote_addr;
end

local_ip = ‘1.1.1.1’

redis_instance:select(2)
ip_lists = redis_instance:get(‘ip_lists’)
ip_lists = {“1.1.1.1”, “2.2.2.2”}

— 不是数组则直接转向生产环境
— if(type(ip_lists) ~= table)
— then
—    ngx.exec(“/gray_online”);
— end

local hit_ip = false
for k,v in pairs(ip_lists) do
if v == local_ip then
    hit_ip = true
end
end

— 判断是否在白名单然后转到对应服务
if hit_ip == true then
ngx.exec(“/gray_develop”);
else
ngx.exec(“/gray_online”);
end

local ok,err=redis_instance:close();

    原文作者:渔阳吃大苹果
    原文地址: https://segmentfault.com/a/1190000018855766
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞