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

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

mhr18 2025-04-30 18:07 18 浏览 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.log(ngx.INFO,"uri:",request_uri," send ios upgrade response")
                send_upgrade(iosMinVersion,clientType)
                return;
            end
        else if clientType == 200 and andoridMinVersion ~= nil 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.log(ngx.INFO, "用户ID灰度(YES):", " userId:", userId, " ratio:", ratio, " upstream:", ngx.var.target)
        else
            ngx.log(ngx.INFO, "用户ID灰度(NO):", " 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

相关推荐

redis 7.4.3更新!安全修复+性能优化全解析

一、Redis是什么?为什么选择它?Redis(RemoteDictionaryServer)是一款开源的高性能内存键值数据库,支持持久化、多数据结构(如字符串、哈希、列表等),广泛应用于缓存、消...

C# 读写Redis数据库的简单例子

CSRedis是一个基于C#的Redis客户端库,它提供了与Redis服务器进行交互的功能。它是一个轻量级、高性能的库,易于使用和集成到C#应用程序中。您可以使用NuGet包管理器或使用以下命令行命令...

十年之重修Redis原理

弱小和无知并不是生存的障碍,傲慢才是。--------面试者总结Redis可能都用过,但是从来没有理解过,就像一个熟悉的陌生人,本文主要讲述了Redis基本类型的使用、数据结构、持久化、单线程模型...

高频L2行情数据Redis存储架构设计(含C++实现代码)

一、Redis核心设计原则内存高效:优化数据结构,减少内存占用低延迟访问:单次操作≤0.1ms响应时间数据完整性:完整存储所有L2字段实时订阅:支持多客户端实时数据推送持久化策略:RDB+AOF保障数...

Magic-Boot开源引擎:零代码玩转企业级开发,效率暴涨!

一、项目介绍基于magic-api搭建的快速开发平台,前端采用Vue3+naive-ui最新版本搭建,依赖较少,运行速度快。对常用组件进行封装。利用Vue3的@vue/compiler-sfc单文...

项目不行简历拉胯?3招教你从面试陪跑逆袭大厂offer!

项目不行简历拉胯?3招教你从面试陪跑逆袭大厂offer!老铁们!是不是每次面试完都感觉自己像被大厂面试官婉拒的渣男?明明刷了三个月题库,背熟八股文,结果一被问项目就支支吾吾,简历写得像大学生课程设计?...

谷歌云平台:开发者部署超120个开源包

从国外相关报道了解,Google与Bitnami合作为Google云平台增加了一个新的功能,为了方便开发人员快捷部署程序,提供了120余款开源应用程序云平台的支持。这些应用程序其中包括了WordPre...

知名互联网公司和程序员都看好的数据库是什么?

2017年数据库领域的最大趋势是什么?什么是最热的数据处理技术?学什么数据库最有前途?程序员们普遍不喜欢的数据库是什么?本文都会一一揭秘。大数据时代,数据库的选择备受关注,此前本号就曾揭秘国内知名互联...

腾讯云发布云存储MongoDB服务

近日,著名安全专家兼Shodan搜索引擎的创建者JohnMatherly发现,目前至少有35000个受影响的MongoDB数据库暴露在互联网上,它们所包含的数据暴露在网络攻击风险之中。据估计,将近6...

已跪,Java全能笔记爆火,分布式/开源框架/微服务/性能调优全有

前言程序员,立之根本还是技术,一个程序员的好坏,虽然不能完全用技术强弱来判断,但是技术水平一定是基础,技术差的程序员只能CRUD,技术不深的程序员也成不了架构师。程序员对于技术的掌握,除了从了解-熟悉...

面试官:举个你解决冲突的例子?别怂!用这个套路……

面试官:举个你解决冲突的例子?别怂!用这个套路……最近收到粉丝私信,说被问到:团队技术方案有分歧怎么办?当场大脑宕机……兄弟!这不是送命题,是展示你情商+技术判断力的王炸题!今天教你们3招,用真实案例...

面试碰到MongoDB?莫慌,跟面试官这样吹MongoDB 复制集

推荐阅读:吊打MySQL:21性能优化实践+学习导图+55面试+笔记+20高频知识点阿里一线架构师分享的技术图谱,进阶加薪全靠它十面字节跳动,依旧空手而归,我该放弃吗?文末会分享一些MongoDB的学...

SpringBoot集成扩展-访问NoSQL数据库之Redis和MongoDB!

与关系型数据库一样,SpringBoot也提供了对NoSQL数据库的集成扩展,如对Redis和MongoDB等数据库的操作。通过默认配置即可使用RedisTemplate和MongoTemplate...

Java程序员找工作总卡项目关?

Java程序员找工作总卡项目关?3招教你用真实经历写出HR抢着要的简历!各位Java老哥,最近刷招聘软件是不是手都划酸了?简历投出去石沉大海,面试邀请却总在飞别人的简历?上周有个兄弟,13年经验投了5...

Java多租户SaaS系统实现方案

嗯,用户问的是Java通过租户id实现的SaaS方案。首先,我需要理解用户的需求。SaaS,也就是软件即服务,通常是指多租户的架构,每个租户的数据需要隔离。用户可能想知道如何在Java中利用租户ID来...

取消回复欢迎 发表评论: