百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Openresty灰度发布及版本约束(openresty 灰度)

off999 2025-04-11 04:32 52 浏览 0 评论

目标

利用openresty配合Lua脚本实现基于redis配置进行灰度发布及最小版本约束。实现如下功能:
1、随机灰度
2、基于用户ID灰度(用户ID%100<Radio)
3、基于指定用户ID灰度(例如用户ID:2、3)
4、基于App版本号进行灰度(例如内部版本号:31)
5、全量灰度
6、App最小版本约束

代码约束

1、App请求头中携带客户端类型(X-App-Type)、客户端版本号(X-App-Version)
2、App请求头中携带Token信息(X-Client-Token),用于获取用户ID(测试脚本中token生成规则为 userid_token),实际使用中,需要根据token机制进行用户ID转换(修改getUserId方法)
3、代码中自动忽略了版本号为空或为0的情况,如果需要判断,需要修改分发逻辑
4、通过修改send_upgrade方法,自行配置版本过低的提示
5、客户端版本号为数字
6、客户端类型为数字;代码中100:代表ios 200:代表android

Redis 配置参考(gray.config)

{
    "ratio": "30",
    "minVersion": "1",
    "versions": [
        "10"
    ],
    "type": 1,
    "gray": "192.168.1.2:8080",
    "default": "192.168.1.2:8081",
    "userIds": [
        "1"
    ]
}

Nginx 全局配置

 增加如下代码
....
http{
  ....
  lua_code_cache on;
  lua_shared_dict gray_cache 10m;
  ....
}

Nginx 转发配置

server {
   listen       80;
   location / {
     set $target '';
     default_type text/html;
     proxy_set_header    X-Real-IP $remote_addr;
     proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
     access_by_lua_file /etc/nginx/lua/gray.lua;
     proxy_pass http://$target$request_uri;
   }
}

Lua脚本

local redis = require "resty.redis";
local cjson = require("cjson")
local function isEmpty(s)
    return s == nil or s == ''
end
local function stringToInt(str)
    if isEmpty(str) then
        return 0
    end
    local number = tonumber(str)
    if not number then
        return 0
    end
    return number
end
local function left(str, split)
    local index = string.find(str, split)
    if not index then
        return nil
    end
    local result = string.sub(str, 0, index - 1)
    return result
end
local function getUserId()
    -- 根据token计算用户ID,需根据自己的业务就行替换
    local token = ngx.req.get_headers()["X-Client-Token"]
    if isEmpty(token) then
        return 0
    end
    local uidStr = left(token, "_")
    if isEmpty(uidStr) then
        return 0
    end
    return stringToInt(uidStr)
end
local function getClientVersion()
    local version = ngx.req.get_headers()["X-App-Version"]
    return stringToInt(version)
end
local function getClientType()
    -- 客户端类型,在这个地方 100表示ios 200表示 安卓
    local version = ngx.req.get_headers()["X-App-Type"]
    return stringToInt(version)
end
local function close_redis(redis_cluster)
    if not redis_cluster then
        return
    end
    local pool_max_idle_time = 10000
    local pool_size = 100
    local ok, err = redis_cluster:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        ngx.log(ngx.ERR, "set keepalive fail ", err)
    end
end
local function read_gray_config(address, port, password, key, default_config)
    local redis_cache = redis:new();
    redis_cache:set_timeout(1000);
    local ok, err = redis_cache:connect(address, port);
    if not ok then
        close_redis(redis_cache)
        ngx.log(ngx.ERR, "redis 连接错误: ", err)
        return default_config;
    end
    if not isEmpty(password) then
        local ok, err = redis_cache:auth(password)
        if not ok then
            ngx.log(ngx.ERR, "redis 携带密码连接错误: ", err)
            close_redis(redis_cache)
            return default_config;
        end
    end
    local res, err = redis_cache:get(key)
    if not res then
        ngx.log(ngx.ERR, "redis读取数据错误: ", err)
        close_redis(redis_cache)
        return default_config
    end
    local json = cjson.new()
    if not json then
        ngx.log(ngx.ERR, "创建json错误 ")
        close_redis(redis_cache)
        return default_config
    end
    if res == ngx.null then
        local ok, err = redis_cache:set(key, json.encode(default_config))
        if not ok then
            ngx.log(ngx.ERR, "写入默认配置出错: ", err)
        end
        ngx.log(ngx.INFO, "灰度配置为空,采用默认配置")
        close_redis(redis_cache)
        return default_config
    else
        close_redis(redis_cache)
        return json.decode(res)
    end
end
local function load_gray(address, port, password, timeout, key, default_config)
    local share_cache = ngx.shared.gray_cache
    local cache_data = share_cache:get("config")
    local json = cjson.new()
    if not json then
        ngx.log(ngx.ERR, "创建json对象错误 ")
        return default_config
    end
    if cache_data == nil then
        cache_data = read_gray_config(address, port, password, key, default_config)
        if cache_data == nil then
            ngx.log(ngx.ERR, "获取配置信息返回null")
        else
            local ok, err = share_cache:set("config", json.encode(cache_data), timeout)
            if not ok then
                ngx.log(ngx.INFO, "刷新本地灰度配置信息失败", err)
            else
                ngx.log(ngx.INFO, "刷新本地灰度配置信息成功")
            end
        end
        return cache_data
    else
        ngx.log(ngx.INFO, "采用缓存配置信息")
        return json.decode(cache_data)
    end
end
local default_cache = {
    type = 0, -- 灰度类型 0、关闭灰度 1、随机灰度 2、根据用户ID灰度 3、指定用户ID灰度 4、指定用户版本灰度 5、全量灰度
    default = "192.168.1.2:8080", -- 正常分发地址
    gray = "192.168.1.2:8081", -- 灰度分发地址
    userIds = { "0" }, -- 灰度用户ID,例如:{"2","3","4"}
    ratio = "0", -- 灰度分发比例
    minVersion = "0", -- 客户端最小版本号
    versions = { "0" } -- 灰度版本号,例如:{"30","31"}
}
local function contains(value, list)
    if list == nil or isEmpty(value) then
        return false
    end
    for k, v in ipairs(list) do
        if v == value then
            return true;
        end
    end
    return false;
end
-- 发送版本过低消息
local function send_upgrade(minVersion,clientType)
    local upgrade_response = '{"code":403,"data":{"version":"0","message":"您当前的版本过低,请升级到最新版本!"}}'
    ngx.header.content_type = "application/json"
    ngx.say(string.format(upgrade_response,clientType,minVersion,minVersion))
end
local gray = load_gray("127.0.0.1", 6379, "", 10, "gray.config", default_cache)
if gray then
    ngx.var.target = gray["default"]
    local gray_type = gray["type"]
    local iosMinVersion = gray["iosMinVersion"]
    local andoridMinVersion = gray["andoridMinVersion"]
    local clientType = getClientType()
    local request_uri = ngx.var.request_uri
    if (string.find(request_uri, "^/yuliao/uri/") == nil) then
        local clientVersion = getClientVersion()
        if clientType == 100 and iosMinVersion ~= nil and iosMinVersion > 0 then
            -- 判断ios最小版本
            local clientVersion = getClientVersion()
            if clientVersion > 0 and clientVersion < iosminversion then ngx.logngx.infouri:request_uri send ios upgrade response send_upgradeiosminversionclienttype return end else if clienttype='= 200' and andoridminversion and andoridminversion> 0 then
            -- 判断安卓最小版本
            if clientVersion > 0 and clientVersion < andoridMinVersion and clientVersion ~= 1 then
                ngx.log(ngx.INFO,"uri:",request_uri," send android upgrade response")
                send_upgrade(andoridMinVersion,clientType)
                return;
            end
        end
    end
    end
    if gray_type == 1 then
        -- 随机灰度
        local ratio = stringToInt(gray["ratio"])
        local number = math.random(100) % 100
        if number < ratio then
            ngx.var.target = gray["gray"]
            ngx.log(ngx.INFO, "随机灰度(YES):", " number:", number, " ratio:", ratio, " upstream:", ngx.var.target)
        else
            ngx.log(ngx.INFO, "随机灰度(NO):", " number:", number, " ratio:", ratio, " upstream:", ngx.var.target)
        end
    elseif gray_type == 2 then
        -- 用户ID灰度
        local ratio = stringToInt(gray["ratio"])
        local userId = getUserId()
        local number = userId % 100
        if number < ratio then ngx.var.target='gray["gray"]' ngx.logngx.info idyes: userid: userid ratio: ratio upstream: ngx.var.target else ngx.logngx.info idno: userid: userid ratio: ratio upstream: ngx.var.target end elseif gray_type='= 3' then -- id local userid='getUserId()' if userid> 0 then
            userId = tostring(userId)
            local userIds = gray["userIds"]
            if contains(userId, userIds) then
                ngx.var.target = gray["gray"]
                ngx.log(ngx.INFO, "指定用户灰度(YES):", " userId:", userId, " upstream:", ngx.var.target)
            else
                ngx.log(ngx.INFO, "指定用户灰度(NO):", " userId:", userId, " upstream:", ngx.var.target)
            end
        else
            ngx.log(ngx.INFO, "指定用户灰度(NO):", " userId:", userId, " upstream:", ngx.var.target)
        end
    elseif gray_type == 4 then
        -- 指定用户版本灰度
        if version > 0 then
            local versions = gray["versions"]
            version = tostring(version)
            if contains(version, versions) then
                ngx.var.target = gray["gray"]
                ngx.log(ngx.INFO, "指定版本灰度(YES):", " version:", version, " upstream:", ngx.var.target)
            else
                ngx.log(ngx.INFO, "指定版本灰度(NO):", " version:", version, " upstream:", ngx.var.target)
            end
        else
            ngx.log(ngx.INFO, "指定版本灰度(NO):", " version:", version, " upstream:", ngx.var.target)
        end
    elseif gray_type == 5 then
        ngx.var.target = gray["gray"]
        ngx.log(ngx.INFO, "系统全量灰度(YES):", " upstream:", ngx.var.target)
    end
else
    local json = cjson.new()
    ngx.header.content_type = "application/json"
    ngx.say(cjson.encode({ code = 500, message = '无法找到转发配置,请联系管理员!' }))
    ngx.log(ngx.ERR, "无法找到系统配信息,返回500")
end

相关推荐

电脑wifi突然变成红叉搜不到

1、WiFi功能未开启:很多时候出现WiFi红色叉叉图标,可能就是无线WiFi的开关或者按键没有开启导致的。一般的笔记本键盘上面都有一个F5开启WiFi的功能,有的需要结合Fn功能键一起按。每个品牌的...

正版win10系统一键重装官网(一键装机win10正版系统)

1、下载小白一键重装软件,打开软件后选择我们要安装的系统。?2、接着小白给出我们一些常用的电脑软件,大家可根据自己需要进行下载。?3、然后就是我们就耐心的等待系统镜像的下载吧。?4、部署环境完成后我们...

windows8系统自己怎么装(如何安装windows 8)

要在线安装Windows8系统,您可以按照以下步骤操作:1.准备安装媒体:在您的计算机上打开一个现代的网络浏览器(如Chrome、Firefox或Edge),然后前往Microsoft...

win10登录选项没有密码设置(win10没有登陆密码框)

是该电脑没设置密码,所以登录时看不到密码选项。电脑开机后,要设置密码,设置完成后,重新启动电脑,就会出现密码登录框,输入密码并正确后,电脑才能正常进入系统。1、首先进入安全模式;进入安全模式教程:2、...

小白刷机官网(小白刷机助手)

平板的话,和处理器有关,如果处理器只支持win8是不能刷win10的。

windows关闭端口命令(windows 关端口)

1、点击控制面板。2、进入控制面板,然后点击系统和安全。3、进入系统和安全,点击Windows防火墙。4、进入Windows防火墙,点击左侧的高级设置。5、进入防火墙高级设置,点击入站规则。6、点击入...

360免费wifi老版本(360免费wifi2019下载安装)
  • 360免费wifi老版本(360免费wifi2019下载安装)
  • 360免费wifi老版本(360免费wifi2019下载安装)
  • 360免费wifi老版本(360免费wifi2019下载安装)
  • 360免费wifi老版本(360免费wifi2019下载安装)
无线wifi路由器怎么安装(请问无线路由器怎么安装)

安装的方法/步骤:1、怎么安装无线路由器呢?首先把网线的其中一头插入进光猫里面。2、接着用网线的另一头插入进无线路由器的蓝色接口处,这样就安装好无线路由器啦。3、点击打开电脑浏览器,输入路由器设置地址...

fat32格式化精灵(格式化fat32格式工具)

内存卡格式化一般有两种方式:第一种是直接将内存卡插入手机的卡托,然后进入设置——运行及内存管理,点击格式化SD卡即可完成。当然有一些手机是不支持外置的内存卡插入,这就需要用OTG线插入手机,点击手机的...

外置光驱安装win7系统(外置光驱安装操作系统)

苹果电脑、电源适配器丶光盘装系统(电脑有光驱、或者外接光驱)光盘安装准备:win764位纯净版安装盘,如果使用的苹果电脑有光驱,优先使用自带光驱安装;如电脑没有光驱,可以是用外接USB光驱安装。光盘...

win7x86是32位还是64位

32位win7x86是32位操作系统,win7x64是64位操作系统。扩展资料Windows7,中文名称视窗7,是由微软公司(Microsoft)开发的操作系统,内核版本号为WindowsNT...

用我告诉你安装win7(安装win7教程)

方法一:使用工具在线一键下载安装win7(win7正式版只需使用正版密钥激活即可)1、在电脑安装好小白一键重装系统工具打开,选择原版win7旗舰版系统,点击安装此系统。2、等待软件自动下载系统镜像文件...

sd卡如何修复(如何修复sd卡视频教程)

修复SD卡的三个步骤如下:1.使用磁盘检测工具检查SD卡的错误:您可以使用Windows操作系统中自带的磁盘检查工具或第三方软件来检查并修复SD卡中的错误。2.格式化SD卡:如果检查后发现错误无法...

安卓手机杀毒软件哪个最好用

腾讯手机管家的守护老人安全功能版本我在用,我来说说吧。此版本是专门为守护老人安全设计推出的,不但有效拦截诈骗短信,电话,木马病毒,钓鱼网址,辟谣功能可以帮助老人立即分辨养生讯息,银行卡故障讯息,保险异...

xp3用什么模拟器打开(xp3用什么模拟器打开好)

可以按照以下的步骤排查解决:首先,游戏必须要使kirikiri引擎,这点可以从文件中是否含有部分xp3后缀的文件来判断然后用模拟器打开date.xp3就行了,部分汉化游戏是直接打开exe程序如果遇到d...

取消回复欢迎 发表评论: