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

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

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

相关推荐

Python钩子函数实现事件驱动系统(created钩子函数)

钩子函数(HookFunction)是现代软件开发中一个重要的设计模式,它允许开发者在特定事件发生时自动执行预定义的代码。在Python生态系统中,钩子函数广泛应用于框架开发、插件系统、事件处理和中...

Python函数(python函数题库及答案)

定义和基本内容def函数名(传入参数):函数体return返回值注意:参数、返回值如果不需要,可以省略。函数必须先定义后使用。参数之间使用逗号进行分割,传入的时候,按照顺序传入...

Python技能:Pathlib面向对象操作路径,比os.path更现代!

在Python编程中,文件和目录的操作是日常中不可或缺的一部分。虽然,这么久以来,钢铁老豆也还是习惯性地使用os、shutil模块的函数式API,这两个模块虽然功能强大,但在某些情况下还是显得笨重,不...

使用Python实现智能物流系统优化与路径规划

阅读文章前辛苦您点下“关注”,方便讨论和分享,为了回馈您的支持,我将每日更新优质内容。在现代物流系统中,优化运输路径和提高配送效率是至关重要的。本文将介绍如何使用Python实现智能物流系统的优化与路...

Python if 语句的系统化学习路径(python里的if语句案例)

以下是针对Pythonif语句的系统化学习路径,从零基础到灵活应用分为4个阶段,包含具体练习项目和避坑指南:一、基础认知阶段(1-2天)目标:理解条件判断的逻辑本质核心语法结构if条件:...

[Python] FastAPI基础:Path路径参数用法解析与实例

查询query参数(上一篇)路径path参数(本篇)请求体body参数(下一篇)请求头header参数本篇项目目录结构:1.路径参数路径参数是URL地址的一部分,是必填的。路径参...

Python小案例55- os模块执行文件路径

在Python中,我们可以使用os模块来执行文件路径操作。os模块提供了许多函数,用于处理文件和目录路径。获取当前工作目录(CurrentWorkingDirectory,CWD):使用os....

python:os.path - 常用路径操作模块

应该是所有程序都需要用到的路径操作,不废话,直接开始以下是常用总结,当你想做路径相关时,首先应该想到的是这个模块,并知道这个模块有哪些主要功能,获取、分割、拼接、判断、获取文件属性。1、路径获取2、路...

原来如此:Python居然有6种模块路径搜索方式

点赞、收藏、加关注,下次找我不迷路当我们使用import语句导入模块时,Python是怎么找到这些模块的呢?今天我就带大家深入了解Python的6种模块路径搜索方式。一、Python模块...

每天10分钟,python进阶(25)(python进阶视频)

首先明确学习目标,今天的目标是继续python中实例开发项目--飞机大战今天任务进行面向对象版的飞机大战开发--游戏代码整编目标:完善整串代码,提供完整游戏代码历时25天,首先要看成品,坚持才有收获i...

python 打地鼠小游戏(打地鼠python程序设计说明)

给大家分享一段AI自动生成的代码(在这个游戏中,玩家需要在有限时间内打中尽可能多的出现在地图上的地鼠),由于我现在用的这个电脑没有安装sublime或pycharm等工具,所以还没有测试,有兴趣的朋友...

python线程之十:线程 threading 最终总结

小伙伴们,到今天threading模块彻底讲完。现在全面总结threading模块1、threading模块有自己的方法详细点击【threading模块的方法】threading模块:较低级...

Python信号处理实战:使用signal模块响应系统事件

信号是操作系统用来通知进程发生了某个事件的一种异步通信方式。在Python中,标准库的signal模块提供了处理这些系统信号的机制。信号通常由外部事件触发,例如用户按下Ctrl+C、子进程终止或系统资...

Python多线程:让程序 “多线作战” 的秘密武器

一、什么是多线程?在日常生活中,我们可以一边听音乐一边浏览新闻,这就是“多任务处理”。在Python编程里,多线程同样允许程序同时执行多个任务,从而提升程序的执行效率和响应速度。不过,Python...

用python写游戏之200行代码写个数字华容道

今天来分析一个益智游戏,数字华容道。当初对这个游戏颇有印象还是在最强大脑节目上面,何猷君以几十秒就完成了这个游戏。前几天写2048的时候,又想起了这个游戏,想着来研究一下。游戏玩法用尽量少的步数,尽量...

取消回复欢迎 发表评论: