HackOwnLife

灰度发布功能

2026/06/09
16
0

灰度发布功能设计方案

一、架构概述

1.1 整体架构

客户端请求
↓
Nginx/负载均衡器 (统一入口)
↓
[灰度路由判断] ← Redis灰度配置
↓
稳定版实例 / 灰度版实例

1.2 核心思路

  • 灰度维度: 基于员工ID(Employee ID)进行流量划分
  • 部署方式: 多实例部署(稳定版 + 灰度版),通过端口或域名区分
  • 配置管理: Redis存储灰度规则,支持动态更新
  • 路由位置: Nginx层根据用户标识转发到不同实例

二、数据库设计

2.1 灰度配置表(可选,用于持久化)

文件: sql/gray_release_config.sql

CREATE TABLE `t_gray_release_config` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
  `config_key` VARCHAR(50) NOT NULL COMMENT '配置键: gray_enabled, gray_percentage等',
  `config_value` VARCHAR(500) NOT NULL COMMENT '配置值',
  `description` VARCHAR(200) DEFAULT NULL COMMENT '描述',
  `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_config_key` (`config_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='灰度发布配置表';

-- 初始化数据
INSERT INTO `t_gray_release_config` (`config_key`, `config_value`, `description`) VALUES
('gray_enabled', 'false', '灰度开关'),
('gray_percentage', '0', '灰度流量百分比(0-100)'),
('gray_version', 'v2.33', '当前灰度版本号');

2.2 灰度用户白名单表

文件: sql/gray_user_whitelist.sql

CREATE TABLE `t_gray_user_whitelist` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
  `employee_id` BIGINT NOT NULL COMMENT '员工ID',
  `employee_name` VARCHAR(50) DEFAULT NULL COMMENT '员工姓名(冗余)',
  `reason` VARCHAR(200) DEFAULT NULL COMMENT '加入灰度原因',
  `operator_id` BIGINT DEFAULT NULL COMMENT '操作人ID',
  `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_employee_id` (`employee_id`),
  KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='灰度用户白名单表';

三、Redis数据结构设计

3.1 Redis Key规范

gray:config:enabled          -> String: "true" / "false"
gray:config:percentage       -> String: "10" (0-100)
gray:config:version          -> String: "v2.33"
gray:whitelist               -> Set: {1001, 1002, 1003} (员工ID集合)
gray:blacklist               -> Set: {2001, 2002} (明确不使用灰度的员工)
gray:metrics:request_count   -> Hash: {stable: 1000, gray: 100}

3.2 缓存策略

  • TTL: 灰度配置不设置过期时间,永久有效
  • 更新机制: 修改配置后立即更新Redis,无需重启应用
  • 读取性能: O(1)复杂度,不影响请求响应时间

四、后端实现

4.1 灰度配置实体类

文件: GrayReleaseConfig.java

package com.fesh.model.dao;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;

@Data
@TableName("t_gray_release_config")
public class GrayReleaseConfig {
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    private String configKey;
    private String configValue;
    private String description;
    private Date createTime;
    private Date updateTime;
}

文件: GrayUserWhitelist.java

package com.fesh.model.dao;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;

@Data
@TableName("t_gray_user_whitelist")
public class GrayUserWhitelist {
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    private Long employeeId;
    private String employeeName;
    private String reason;
    private Long operatorId;
    private Date createTime;
    private Date updateTime;
}

4.2 Mapper接口

文件: GrayReleaseConfigMapper.java

package com.fesh.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fesh.model.dao.GrayReleaseConfig;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface GrayReleaseConfigMapper extends BaseMapper<GrayReleaseConfig> {
}

文件: GrayUserWhitelistMapper.java

package com.fesh.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fesh.model.dao.GrayUserWhitelist;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface GrayUserWhitelistMapper extends BaseMapper<GrayUserWhitelist> {
}

4.3 灰度服务接口

文件: GrayReleaseService.java

package com.fesh.service;

import java.util.List;

public interface GrayReleaseService {
  
    /**
     * 判断员工是否应该使用灰度版本
     * @param employeeId 员工ID
     * @return true-灰度版本, false-稳定版本
     */
    boolean isGrayUser(Long employeeId);
  
    /**
     * 获取灰度配置
     * @return 配置Map
     */
    java.util.Map<String, Object> getGrayConfig();
  
    /**
     * 更新灰度开关
     * @param enabled 是否启用
     */
    void updateGrayEnabled(boolean enabled);
  
    /**
     * 更新灰度百分比
     * @param percentage 百分比(0-100)
     */
    void updateGrayPercentage(int percentage);
  
    /**
     * 添加员工到灰度白名单
     * @param employeeId 员工ID
     * @param reason 原因
     */
    void addToWhitelist(Long employeeId, String reason);
  
    /**
     * 从灰度白名单移除员工
     * @param employeeId 员工ID
     */
    void removeFromWhitelist(Long employeeId);
  
    /**
     * 获取灰度白名单列表
     * @return 白名单列表
     */
    List<com.fesh.model.dao.GrayUserWhitelist> getWhitelist();
  
    /**
     * 同步配置到Redis
     */
    void syncConfigToRedis();
}

4.4 灰度服务实现

文件: GrayReleaseServiceImpl.java

package com.fesh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fesh.mapper.GrayReleaseConfigMapper;
import com.fesh.mapper.GrayUserWhitelistMapper;
import com.fesh.model.dao.GrayReleaseConfig;
import com.fesh.model.dao.GrayUserWhitelist;
import com.fesh.service.GrayReleaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class GrayReleaseServiceImpl implements GrayReleaseService {
  
    @Autowired
    private GrayReleaseConfigMapper configMapper;
  
    @Autowired
    private GrayUserWhitelistMapper whitelistMapper;
  
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
  
    private static final String REDIS_GRAY_ENABLED = "gray:config:enabled";
    private static final String REDIS_GRAY_PERCENTAGE = "gray:config:percentage";
    private static final String REDIS_GRAY_VERSION = "gray:config:version";
    private static final String REDIS_GRAY_WHITELIST = "gray:whitelist";
    private static final String REDIS_GRAY_BLACKLIST = "gray:blacklist";
  
    @Override
    public boolean isGrayUser(Long employeeId) {
        try {
            // 1. 检查灰度开关
            Boolean enabled = (Boolean) redisTemplate.opsForValue().get(REDIS_GRAY_ENABLED);
            if (enabled == null || !enabled) {
                return false;
            }
  
            // 2. 检查黑名单
            Boolean inBlacklist = redisTemplate.opsForSet().isMember(REDIS_GRAY_BLACKLIST, employeeId);
            if (inBlacklist != null && inBlacklist) {
                return false;
            }
  
            // 3. 检查白名单(白名单优先级最高)
            Boolean inWhitelist = redisTemplate.opsForSet().isMember(REDIS_GRAY_WHITELIST, employeeId);
            if (inWhitelist != null && inWhitelist) {
                return true;
            }
  
            // 4. 按百分比随机分配
            Object percentageObj = redisTemplate.opsForValue().get(REDIS_GRAY_PERCENTAGE);
            if (percentageObj != null) {
                int percentage = Integer.parseInt(percentageObj.toString());
                if (percentage > 0) {
                    // 使用员工ID作为种子,保证同一员工始终分配到相同版本
                    int hash = Math.abs(employeeId.hashCode()) % 100;
                    return hash < percentage;
                }
            }
  
            return false;
        } catch (Exception e) {
            log.error("判断灰度用户失败, employeeId: {}", employeeId, e);
            // 异常情况下默认返回稳定版
            return false;
        }
    }
  
    @Override
    public Map<String, Object> getGrayConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("enabled", redisTemplate.opsForValue().get(REDIS_GRAY_ENABLED));
        config.put("percentage", redisTemplate.opsForValue().get(REDIS_GRAY_PERCENTAGE));
        config.put("version", redisTemplate.opsForValue().get(REDIS_GRAY_VERSION));
  
        Long whitelistSize = redisTemplate.opsForSet().size(REDIS_GRAY_WHITELIST);
        config.put("whitelistCount", whitelistSize != null ? whitelistSize : 0);
  
        return config;
    }
  
    @Override
    @Transactional
    public void updateGrayEnabled(boolean enabled) {
        // 更新数据库
        LambdaQueryWrapper<GrayReleaseConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GrayReleaseConfig::getConfigKey, "gray_enabled");
        GrayReleaseConfig config = configMapper.selectOne(wrapper);
        if (config != null) {
            config.setConfigValue(String.valueOf(enabled));
            configMapper.updateById(config);
        }
  
        // 更新Redis
        redisTemplate.opsForValue().set(REDIS_GRAY_ENABLED, enabled);
        log.info("灰度开关已更新: {}", enabled);
    }
  
    @Override
    @Transactional
    public void updateGrayPercentage(int percentage) {
        if (percentage < 0 || percentage > 100) {
            throw new IllegalArgumentException("百分比必须在0-100之间");
        }
  
        // 更新数据库
        LambdaQueryWrapper<GrayReleaseConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GrayReleaseConfig::getConfigKey, "gray_percentage");
        GrayReleaseConfig config = configMapper.selectOne(wrapper);
        if (config != null) {
            config.setConfigValue(String.valueOf(percentage));
            configMapper.updateById(config);
        }
  
        // 更新Redis
        redisTemplate.opsForValue().set(REDIS_GRAY_PERCENTAGE, percentage);
        log.info("灰度百分比已更新: {}%", percentage);
    }
  
    @Override
    @Transactional
    public void addToWhitelist(Long employeeId, String reason) {
        // 添加到数据库
        GrayUserWhitelist whitelist = new GrayUserWhitelist();
        whitelist.setEmployeeId(employeeId);
        whitelist.setReason(reason);
        whitelistMapper.insert(whitelist);
  
        // 添加到Redis
        redisTemplate.opsForSet().add(REDIS_GRAY_WHITELIST, employeeId);
        // 如果在黑名单中,先移除
        redisTemplate.opsForSet().remove(REDIS_GRAY_BLACKLIST, employeeId);
  
        log.info("员工 {} 已加入灰度白名单, 原因: {}", employeeId, reason);
    }
  
    @Override
    @Transactional
    public void removeFromWhitelist(Long employeeId) {
        // 从数据库删除
        LambdaQueryWrapper<GrayUserWhitelist> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GrayUserWhitelist::getEmployeeId, employeeId);
        whitelistMapper.delete(wrapper);
  
        // 从Redis删除
        redisTemplate.opsForSet().remove(REDIS_GRAY_WHITELIST, employeeId);
  
        log.info("员工 {} 已从灰度白名单移除", employeeId);
    }
  
    @Override
    public List<GrayUserWhitelist> getWhitelist() {
        LambdaQueryWrapper<GrayUserWhitelist> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(GrayUserWhitelist::getCreateTime);
        return whitelistMapper.selectList(wrapper);
    }
  
    @Override
    public void syncConfigToRedis() {
        // 从数据库加载所有配置到Redis
        List<GrayReleaseConfig> configs = configMapper.selectList(null);
        for (GrayReleaseConfig config : configs) {
            switch (config.getConfigKey()) {
                case "gray_enabled":
                    redisTemplate.opsForValue().set(REDIS_GRAY_ENABLED, 
                        Boolean.parseBoolean(config.getConfigValue()));
                    break;
                case "gray_percentage":
                    redisTemplate.opsForValue().set(REDIS_GRAY_PERCENTAGE, 
                        Integer.parseInt(config.getConfigValue()));
                    break;
                case "gray_version":
                    redisTemplate.opsForValue().set(REDIS_GRAY_VERSION, 
                        config.getConfigValue());
                    break;
            }
        }
  
        // 加载白名单
        List<GrayUserWhitelist> whitelists = whitelistMapper.selectList(null);
        if (!whitelists.isEmpty()) {
            Object[] employeeIds = whitelists.stream()
                .map(w -> (Object) w.getEmployeeId())
                .toArray();
            redisTemplate.opsForSet().add(REDIS_GRAY_WHITELIST, employeeIds);
        }
  
        log.info("灰度配置已同步到Redis");
    }
}

4.5 灰度管理Controller

文件: GrayReleaseController.java

package com.fesh.controller;

import com.fesh.controller.base.BaseController;
import com.fesh.model.dao.GrayUserWhitelist;
import com.fesh.model.vo.result.ApiResult;
import com.fesh.service.GrayReleaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Api(tags = "灰度发布管理")
@RestController
@RequestMapping("/gray")
public class GrayReleaseController extends BaseController {
  
    @Autowired
    private GrayReleaseService grayReleaseService;
  
    @GetMapping("/config")
    @ApiOperation("获取灰度配置")
    public ApiResult<Map<String, Object>> getConfig() {
        return success(grayReleaseService.getGrayConfig());
    }
  
    @PostMapping("/enabled")
    @ApiOperation("更新灰度开关")
    public ApiResult<Boolean> updateEnabled(@RequestParam boolean enabled) {
        grayReleaseService.updateGrayEnabled(enabled);
        return success(true);
    }
  
    @PostMapping("/percentage")
    @ApiOperation("更新灰度百分比")
    public ApiResult<Boolean> updatePercentage(@RequestParam int percentage) {
        grayReleaseService.updateGrayPercentage(percentage);
        return success(true);
    }
  
    @PostMapping("/whitelist/add")
    @ApiOperation("添加员工到灰度白名单")
    public ApiResult<Boolean> addToWhitelist(@RequestParam Long employeeId, 
                                              @RequestParam(required = false) String reason) {
        grayReleaseService.addToWhitelist(employeeId, reason);
        return success(true);
    }
  
    @DeleteMapping("/whitelist/remove")
    @ApiOperation("从灰度白名单移除员工")
    public ApiResult<Boolean> removeFromWhitelist(@RequestParam Long employeeId) {
        grayReleaseService.removeFromWhitelist(employeeId);
        return success(true);
    }
  
    @GetMapping("/whitelist")
    @ApiOperation("获取灰度白名单列表")
    public ApiResult<List<GrayUserWhitelist>> getWhitelist() {
        return success(grayReleaseService.getWhitelist());
    }
  
    @PostMapping("/sync")
    @ApiOperation("同步配置到Redis")
    public ApiResult<Boolean> syncConfig() {
        grayReleaseService.syncConfigToRedis();
        return success(true);
    }
  
    @GetMapping("/check")
    @ApiOperation("检查当前用户是否灰度用户")
    public ApiResult<Boolean> checkCurrentUser() {
        Long employeeId = Long.parseLong(getUserId());
        boolean isGray = grayReleaseService.isGrayUser(employeeId);
        return success(isGray);
    }
}

4.6 应用启动时同步配置

修改文件: Application.java

在 main方法中添加:

// 初始化灰度配置
initGrayReleaseConfig();

private static void initGrayReleaseConfig() {
    try {
        GrayReleaseService grayReleaseService = context.getBean(GrayReleaseService.class);
        grayReleaseService.syncConfigToRedis();
        log.info("灰度配置初始化完成");
    } catch (Exception e) {
        log.warn("灰度配置初始化失败,可能首次启动", e);
    }
}

五、Nginx配置

5.1 Nginx灰度路由配置

文件: /etc/nginx/conf.d/api-gray.conf

upstream api_stable {
    server 127.0.0.1:8080;  # 稳定版实例
}

upstream api_gray {
    server 127.0.0.1:8081;  # 灰度版实例
}

# Lua脚本判断灰度(需要安装lua-nginx-module)
# 如果不想用Lua,可以在应用层处理,见方案B

server {
    listen 80;
    server_name api.com;
  
    location / {
        # 方案A: 使用Lua脚本(推荐,性能最好)
        # set $backend "api_stable";
        # 
        # access_by_lua_block {
        #     local redis = require "resty.redis"
        #     local red = redis:new()
        #     red:set_timeout(1000)
        #     red:connect("127.0.0.1", 6379)
        #   
        #     -- 获取员工ID(从JWT token解析或请求参数)
        #     local employee_id = ngx.var.http_x_employee_id
        #   
        #     if employee_id then
        #         -- 检查白名单
        #         local in_whitelist = red:sismember("gray:whitelist", employee_id)
        #         if in_whitelist == 1 then
        #             ngx.var.backend = "api_gray"
        #         else
        #             -- 检查灰度开关
        #             local enabled = red:get("gray:config:enabled")
        #             if enabled == "true" then
        #                 -- 按百分比分配
        #                 local percentage = tonumber(red:get("gray:config:percentage")) or 0
        #                 local hash = math.abs(tonumber(employee_id)) % 100
        #                 if hash < percentage then
        #                     ngx.var.backend = "api_gray"
        #                 end
        #             end
        #         end
        #     end
        # }
        # 
        # proxy_pass http://$backend;
  
        # 方案B: 简单配置,由应用层判断并返回重定向(次选)
        proxy_pass http://api_stable;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Employee-ID $http_x_employee_id;
    }
}

六、前端/客户端适配

6.1 请求头携带员工ID

确保所有API请求都携带员工标识:

// Axios拦截器示例
axios.interceptors.request.use(config => {
    const employeeId = localStorage.getItem('employeeId');
    if (employeeId) {
        config.headers['X-Employee-ID'] = employeeId;
    }
    return config;
});

6.2 灰度版本提示(可选)

在页面显示灰度标识:

// 检查是否为灰度用户
axios.get('/gray/check').then(res => {
    if (res.data.data) {
        // 显示灰度标识
        document.body.classList.add('gray-version');
    }
});

七、监控与统计

7.1 灰度指标收集

在关键接口添加拦截器记录灰度请求:

文件: GrayMetricsAspect.java

package com.fesh.aspect;

import com.fesh.service.GrayReleaseService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class GrayMetricsAspect {
  
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
  
    @Autowired
    private GrayReleaseService grayReleaseService;
  
    @Around("@annotation(org.springframework.web.bind.annotation.PostMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public Object recordGrayMetrics(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
  
        try {
            // 获取当前用户ID
            String userId = SecurityContextHolder.getContext()
                .getAuthentication().getName();
            Long employeeId = Long.parseLong(userId);
  
            // 判断是否灰度用户
            boolean isGray = grayReleaseService.isGrayUser(employeeId);
  
            // 执行原方法
            Object result = joinPoint.proceed();
  
            // 记录指标
            String key = isGray ? "gray:metrics:gray_request_count" 
                               : "gray:metrics:stable_request_count";
            redisTemplate.opsForValue().increment(key, 1);
  
            long duration = System.currentTimeMillis() - startTime;
            if (duration > 1000) {
                log.warn("灰度请求耗时过长: employeeId={}, isGray={}, duration={}ms", 
                    employeeId, isGray, duration);
            }
  
            return result;
        } catch (Exception e) {
            log.error("灰度指标记录失败", e);
            return joinPoint.proceed();
        }
    }
}

八、部署步骤

8.1 准备两个实例

稳定版 (端口8080):

java -jar console.jar --server.port=8080 --spring.profiles.active=prod

灰度版 (端口8081):

java -jar console.jar --server.port=8081 --spring.profiles.active=prod

8.2 初始化流程

  1. 执行SQL脚本创建表结构
  2. 启动两个应用实例
  3. 访问 /gray/sync 同步配置到Redis
  4. 配置Nginx灰度路由
  5. 重载Nginx: nginx -s reload

8.3 灰度发布流程

1. 部署新版本到灰度实例(8081)
2. 添加测试员工到白名单: POST /gray/whitelist/add?employeeId=1001&reason=测试
3. 验证灰度版本功能正常
4. 逐步增加灰度百分比: POST /gray/percentage?percentage=10 → 30 → 50
5. 观察监控指标和错误日志
6. 全量发布: 将稳定版也升级到新版本
7. 关闭灰度: POST /gray/enabled?enabled=false

九、注意事项

9.1 数据兼容性

  • 灰度版本和稳定版本共享同一数据库,确保数据库变更向下兼容
  • 新增字段要有默认值,避免稳定版报错

9.2 Session共享

  • 使用Redis存储Session,确保用户在两个实例间切换时无感知
  • JWT Token已无状态,天然支持

9.3 回滚策略

  • 灰度出现问题时,立即关闭灰度开关: POST /gray/enabled?enabled=false
  • 或从白名单移除问题用户

9.4 性能影响

  • Redis查询为O(1),对性能影响可忽略(<1ms)
  • 建议Redis与应用在同一内网

十、扩展建议

  1. 灰度规则扩展: 支持按部门、角色、地区等多维度灰度
  2. A/B测试: 记录灰度用户的行为数据,进行效果对比
  3. 自动化灰度: 集成CI/CD,自动执行灰度发布流程
  4. 告警机制: 灰度版本错误率超过阈值时自动关闭灰度