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

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

off999 2025-04-11 04:32 45 浏览 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

相关推荐

u盘怎么取消读写保护(优盘怎么去掉读写保护)

如果您的U盘启动了读写保护,那么就无法进行数据的读取和写入操作。以下是一些可能的解决方法:1.检查开关或按钮:一些U盘有物理开关或按钮,用于启用或禁用读写保护。您可以检查一下U盘上是否有这样的开关或...

打印机脱机无法打印怎么办(打印机脱机无法打印故障处理)
打印机脱机无法打印怎么办(打印机脱机无法打印故障处理)

打印机脱机无法打印怎么办?在使用打印机的过程中,经常会遇到打印机无法打印的问题,如果你的打印机已经正常使用了一段时间,而是现在打印机无法打印了,那么很可能是你的打印机脱机了。我们该怎么办呢?首先我们拿到打印机,要把它的电源线,USB打印线与...

2025-11-12 03:51 off999

台式电脑可以连接wifi吗(台式电脑没有连接wifi选项怎么办)
  • 台式电脑可以连接wifi吗(台式电脑没有连接wifi选项怎么办)
  • 台式电脑可以连接wifi吗(台式电脑没有连接wifi选项怎么办)
  • 台式电脑可以连接wifi吗(台式电脑没有连接wifi选项怎么办)
  • 台式电脑可以连接wifi吗(台式电脑没有连接wifi选项怎么办)
激活码怎么激活(激活码怎么激活steam)

首先,启动电脑,在键盘按下“Win+R”,然后“运行”程序。然后,在“运行”的对话框输入“regedit”,回车确定输入命令然后,在窗口的左侧菜单选择“HKEY_LOCAL_MACHINE\SOFTW...

pscs6安装教程序列号(ps安装序列号cs6破解)
  • pscs6安装教程序列号(ps安装序列号cs6破解)
  • pscs6安装教程序列号(ps安装序列号cs6破解)
  • pscs6安装教程序列号(ps安装序列号cs6破解)
  • pscs6安装教程序列号(ps安装序列号cs6破解)
电脑动不动就卡住不动怎么回事

可能出现卡死原因:1、病毒引起,使你的电脑检测通过的程序太多,CPU主频性能不能充分发挥出来。2、温度过高,散热不好,使CPU性能下降。3、内存条太小,内存缺陷。5、可能设置了开机后自动登陆太多,自动...

笔记本风扇声音大怎么办(笔记本风扇声音非常大)

1.清理笔记本风扇灰尘一般而言,新买来的风扇总是噪声较小,而使用一段时间后会明显变大。其实,灰尘是造成风扇噪音上升的重要原因之一,因为无孔不入的灰尘总能钻进不完全密闭的机箱。当CPU风扇高速旋转时,漩...

如何添加无线网络打印机(如何添加无线网络打印机连接)

  要添加网络打印机,您可以按照以下步骤进行操作:1.确保网络设置:首先,请确保您的计算机和打印机都已连接到同一个局域网或无线网络中,并且网络连接正常。确保您已经知道网络打印...

戴尔电脑一键重装系统(戴尔怎么一键重装系统)

若您需要重装戴尔系统,可以按照以下步骤进行操作:首先备份重要数据,然后获取系统安装介质,可以是光盘或USB驱动器。接下来,进入BIOS设置,将启动顺序调整为从安装介质启动。重启电脑后,按照屏幕提示进行...

电脑ip地址配置异常怎么修复

如果您发现IP地址配置异常,可以按照以下步骤尝试解决:1.检查网络连接:首先检查计算机、路由器或交换机等设备的网线、电源和连接状态是否正常,并确保网络设备正确连接。2.确认IP地址:检查您的计算机...

怎么把win7电脑恢复出厂设置

1.首先我们打开电脑找到“计算机”点击打开。2.进入页面然后我们点击“Windows7(C:)”打开C盘。3.我们在C盘界面找到Windows7并点击打开。4.进入到Win7文件夹中找到并双击“Sys...

ctrl c 和 ctrl v 怎么按(一键复制粘贴)

左手小指按Ctrl键,食指按C键或者V键具体在按Ctrl+C的时候,无名指放在Z键上,中指放在X键上,食指按C键如果你也用这种方式的话,可能和我一样,第一次按的时候不习惯手指这样去分工的感觉,但是你...

u盘格式转换为fat32(U盘格式转换为FAT32)
  • u盘格式转换为fat32(U盘格式转换为FAT32)
  • u盘格式转换为fat32(U盘格式转换为FAT32)
  • u盘格式转换为fat32(U盘格式转换为FAT32)
  • u盘格式转换为fat32(U盘格式转换为FAT32)
玩游戏cpu温度多少正常(玩游戏cpu温度多少正常 贴吧)

在游戏过程中,CPU温度的正常范围通常在40°C至80°C之间。然而,具体的正常温度取决于CPU型号、散热系统和环境条件等因素。一般来说,如果CPU温度超过80°C,就可能存在过热的风险,需要采取措施...

idm下载器(如何卸载idm下载器)

截至2023年9月3日,IDM(InternetDownloadManager)是一款非常受欢迎的下载工具,但它并没有被禁用。IDM可以帮助用户更快速、稳定地下载文件,提供了多线程下载、断点续传等...

取消回复欢迎 发表评论: