Spring Cloud Alibaba - 12 使用Nacos的元数据实现金丝雀发布功能

简介: Spring Cloud Alibaba - 12 使用Nacos的元数据实现金丝雀发布功能

6735aa4777de402592fbe82e8b40ee3d.png

需求


新功能要上线了 , order-center 存在二个版本 V1(老版本) V2(新版本),product-center也存在二个版本V1(老版本) V2新版本 现在需要做到的是order-center(V1)---->product-center(v1),order-center(V2)---->product-center(v2)。


v2版本是小面积部署的,用来测试用户对新版本功能的。若用户完全接受了v2。我们就可以把V1版本卸载完全部署V2版本。


如下调用关系


3cc85ce23ea04d4cb38d47655b7427f9.png


改造


Spring Cloud Alibaba - 11 Ribbon 自定义负载均衡策略(同集群优先权重负载均衡算法) 在这个基础上实现该功能d045c31cf67e4e03bb4ee4cb7a5684ef.png


自定义规则

package com.artisan.customrules;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
 * @author 小工匠
 * @version 1.0
 * @description: 金丝雀版本权重负载均衡策略
 * @date 2022/2/3 13:43
 * @mark: show me the code , change the world
 */
@Slf4j
public class SameClusterPriorityWithVersionRule extends AbstractLoadBalancerRule {
    @Autowired
    private NacosDiscoveryProperties discoveryProperties;
    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
    @Override
    public Server choose(Object key) {
        try {
            //获取本地所部署集群的名称 NJ-CLUSTER
            String localClusterName = discoveryProperties.getClusterName();
            //去nacos上获取和本地 相同集群   相同版本的所有实例信息
            List<Instance> theSameClusterNameAndTheSameVersionInstList = getTheSameClusterAndTheSameVersionInstances(discoveryProperties);
            //声明被调用的实例
            Instance toBeChooseInstance;
            //判断同集群同版本号的微服务实例是否为空
            if(theSameClusterNameAndTheSameVersionInstList.isEmpty()) {
                //跨集群调用相同的版本
                toBeChooseInstance = crossClusterAndTheSameVersionInovke(discoveryProperties);
            }else {
                //具有同集群  同版本号的实例
                toBeChooseInstance = ArtisanWeightedBalancer.chooseInstanceByRandomWeight(theSameClusterNameAndTheSameVersionInstList);
                log.info("同集群同版本调用--->当前微服务所在集群:{},被调用微服务所在集群:{},当前微服务的版本:{},被调用微服务版本:{},Host:{},Port:{}",
                        localClusterName,toBeChooseInstance.getClusterName(),discoveryProperties.getMetadata().get("current-version"),
                        toBeChooseInstance.getMetadata().get("current-version"),toBeChooseInstance.getIp(),toBeChooseInstance.getPort());
            }
            return new NacosServer(toBeChooseInstance);
        } catch (NacosException e) {
            log.error("同集群优先权重负载均衡算法选择异常:{}",e);
            return null;
        }
    }
    /**
     * 方法实现说明:获取相同集群下,相同版本的 所有实例
     * @author:smlz
     * @param discoveryProperties nacos的配置
     * @return: List<Instance>
     * @exception: NacosException
     */
    private List<Instance> getTheSameClusterAndTheSameVersionInstances(NacosDiscoveryProperties discoveryProperties) throws NacosException {
        //当前的集群的名称
        String currentClusterName = discoveryProperties.getClusterName();
        //当前的版本号
        String currentVersion = discoveryProperties.getMetadata().get("current-version");
        //获取所有实例的信息(包括不同集群的,不同版本号的)
        List<Instance> allInstance =  getAllInstances(discoveryProperties);
        List<Instance> theSameClusterNameAndTheSameVersionInstList = new ArrayList<>();
        //过滤相同集群  同版本号的实例
        for(Instance instance : allInstance) {
            if(StringUtils.endsWithIgnoreCase(instance.getClusterName(),currentClusterName)&&
               StringUtils.endsWithIgnoreCase(instance.getMetadata().get("current-version"),currentVersion)) {
                theSameClusterNameAndTheSameVersionInstList.add(instance);
            }
        }
        return theSameClusterNameAndTheSameVersionInstList;
    }
    /**
     * 方法实现说明:获取被调用服务的所有实例
     * @author:smlz
     * @param discoveryProperties nacos的配置
     * @return: List<Instance>
     * @exception: NacosException
     */
    private List<Instance> getAllInstances(NacosDiscoveryProperties discoveryProperties) throws NacosException {
        //第1步:获取一个负载均衡对象
        BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) getLoadBalancer();
        //第2步:获取当前调用的微服务的名称
        String invokedSerivceName = baseLoadBalancer.getName();
        //第3步:获取nacos clinet的服务注册发现组件的api
        NamingService namingService = discoveryProperties.namingServiceInstance();
        //第4步:获取所有的服务实例
        List<Instance> allInstance =  namingService.getAllInstances(invokedSerivceName);
        return allInstance;
    }
    /**
     * 方法实现说明:跨集群环境下 相同版本的
     * @author:smlz
     * @param discoveryProperties
     * @return: List<Instance>
     * @exception: NacosException
     */
    private List<Instance> getCrossClusterAndTheSameVersionInstList(NacosDiscoveryProperties discoveryProperties) throws NacosException {
        //版本号
        String currentVersion = discoveryProperties.getMetadata().get("current-version");
        //被调用的所有实例
        List<Instance> allInstance = getAllInstances(discoveryProperties);
        List<Instance>  crossClusterAndTheSameVersionInstList = new ArrayList<>();
        //过滤相同版本
        for(Instance instance : allInstance) {
            if(StringUtils.endsWithIgnoreCase(instance.getMetadata().get("current-version"),currentVersion)) {
                crossClusterAndTheSameVersionInstList.add(instance);
            }
        }
        return crossClusterAndTheSameVersionInstList;
    }
    private Instance crossClusterAndTheSameVersionInovke(NacosDiscoveryProperties discoveryProperties) throws NacosException {
        //获取所有集群下相同版本的实例信息
        List<Instance>  crossClusterAndTheSameVersionInstList = getCrossClusterAndTheSameVersionInstList(discoveryProperties);
        //当前微服务的版本号
        String currentVersion = discoveryProperties.getMetadata().get("current-version");
        //当前微服务的集群名称
        String currentClusterName = discoveryProperties.getClusterName();
        //声明被调用的实例
        Instance toBeChooseInstance = null ;
        //没有对应相同版本的实例
        if(crossClusterAndTheSameVersionInstList.isEmpty()) {
            log.info("跨集群调用找不到对应合适的版本当前版本为:currentVersion:{}",currentVersion);
            throw new RuntimeException("找不到相同版本的微服务实例");
        }else {
            toBeChooseInstance = ArtisanWeightedBalancer.chooseInstanceByRandomWeight(crossClusterAndTheSameVersionInstList);
            log.info("跨集群同版本调用--->当前微服务所在集群:{},被调用微服务所在集群:{},当前微服务的版本:{},被调用微服务版本:{},Host:{},Port:{}",
                    currentClusterName,toBeChooseInstance.getClusterName(),discoveryProperties.getMetadata().get("current-version"),
                    toBeChooseInstance.getMetadata().get("current-version"),toBeChooseInstance.getIp(),toBeChooseInstance.getPort());
        }
        return toBeChooseInstance;
    }
}


全局规则配置

@Configuration
public class GlobalRibbonConfig {
    @Bean
    public IRule globalConfig() {
        // 根据权重的规则
        // return new ArtisanWeightedRule();
        // 同集群优先调用规则
        // return new SameClusterPriorityRule();
        // 金丝雀版本权重负载均衡策略
        return new SameClusterPriorityWithVersionRule();
    }
}


配置文件

ORDER    --------  BeiJingCluster      V1 
PRODUCT  --------  BeiJingCluster      V1 
PRODUCT  --------  BeiJingCluster      V2
PRODUCT  --------  GuangDongCluster    V1 
PRODUCT  --------  GuangDongCluster    V2


artisan-cloud-customcfg-ribbon-order工程中Nacos的配置如下:

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 1.117.97.88:8848
        cluster-name: BeiJingCluster
        metadata:
          current-version: V1
  application:
    name: artisan-order-center
server:
  port: 8080


服务启动后


a40466f3aed746f39cd77f637f6b0737.png

artisan-cloud-customcfg-ribbon-product工程中Nacos的配置如下:

【BeiJingCluster V1】

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 1.117.97.88:8848
        cluster-name: BeiJingCluster
        metadata:
          current-version: V1
  application:
    name: artisan-product-center
server:
  port: 7777


【BeiJingCluster V2】

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 1.117.97.88:8848
        cluster-name: BeiJingCluster
        metadata:
          current-version: V2
  application:
    name: artisan-product-center
server:
  port: 7778


【GuangDongCluster V1】

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 1.117.97.88:8848
        cluster-name: GuangDongCluster
        metadata:
          current-version: V1
  application:
    name: artisan-product-center
server:
  port: 7779


【GuangDongCluster V2】

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 1.117.97.88:8848
        cluster-name: GuangDongCluster
        metadata:
          current-version: V2
  application:
    name: artisan-product-center
server:
  port: 7780



5e045aaa37ba4cbbadbff23beb62907a.png

验证

访问Order提供的接口,

df39f3e8fd7649dd84a64cfda7d97ddf.png

观察访问日志

2022-02-03 19:06:32.791  INFO 1856 --- [nio-8080-exec-1] c.a.c.SameClusterPriorityWithVe


再看看Product 7777


58b9e2528a304870bfde1be8c85ad619.png


测试结果来看order调用product的时候 优先会调用同集群同版本的product提供的服务。

紧接着,我们把同集群的 同版本的product-center下线,那们就会发生跨集群调用相同的版本

28bd425c1ff644fabb8de8520af9fbe4.png

2c801ff7e11c48f4a54ad8bb1d0999c8.png

再次调用, 观察日志

2022-02-03 19:10:24.754  INFO 1856 --- [nio-8080-exec-4] c.a.c.SameClusterPriorityWithVe


af6ea339a3af41b2870cb1050c0d6b3d.png

说明了当当前集群不存在相同版本的服务时,会跨集群调用相同的版本 。


当我们把Order 也搞个V2 版本


8e7120acdb0f4f8a92a46c335d64e5bd.png

再次调用


4cf4ffb973384b028bccafc60b49fa5c.png

观察日志

481ee914d92f4e52be3e25c457424433.png


源码

https://github.com/yangshangwei/SpringCloudAlibabMaster/tree/master


相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
相关文章
|
8月前
|
人工智能 Java Nacos
基于 Spring AI Alibaba + Nacos 的分布式 Multi-Agent 构建指南
本文将针对 Spring AI Alibaba + Nacos 的分布式多智能体构建方案展开介绍,同时结合 Demo 说明快速开发方法与实际效果。
5139 99
|
9月前
|
XML Java Nacos
Spring Boot 整合Nacos 版本兼容适配 史上最详细文档
本文介绍SpringBoot整合Nacos的完整流程,涵盖Nacos下载安装、配置中心与服务发现集成、版本兼容性问题及实战配置。重点解决SpringBoot 3.3.0与Nacos版本适配难题,推荐使用Spring Cloud Alibaba方案,并提供项目开源地址供参考学习。
|
11月前
|
Dubbo 数据可视化 Java
整合SpringBoot、Dubbo与Nacos:一个快速入门教程
经过上述步骤,消费者模块成功引用了生产者提供的服务,并通过Spring Web将服务映射到了特定的URL路径上。消费者模块成功地调用并展示了生产者提供的数据,并在不移除特定依赖项的情况下确保了系统的正常运行。
|
8月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
735 2
|
消息中间件 缓存 NoSQL
基于Spring Data Redis与RabbitMQ实现字符串缓存和计数功能(数据同步)
总的来说,借助Spring Data Redis和RabbitMQ,我们可以轻松实现字符串缓存和计数的功能。而关键的部分不过是一些"厨房的套路",一旦你掌握了这些套路,那么你就像厨师一样可以准备出一道道饕餮美食了。通过这种方式促进数据处理效率无疑将大大提高我们的生产力。
377 32
|
安全 Java API
Spring Boot 功能模块全解析:构建现代Java应用的技术图谱
Spring Boot不是一个单一的工具,而是一个由众多功能模块组成的生态系统。这些模块可以根据应用需求灵活组合,构建从简单的REST API到复杂的微服务系统,再到现代的AI驱动应用。
1610 8
|
12月前
|
监控 安全 Java
Java 开发中基于 Spring Boot 3.2 框架集成 MQTT 5.0 协议实现消息推送与订阅功能的技术方案解析
本文介绍基于Spring Boot 3.2集成MQTT 5.0的消息推送与订阅技术方案,涵盖核心技术栈选型(Spring Boot、Eclipse Paho、HiveMQ)、项目搭建与配置、消息发布与订阅服务实现,以及在智能家居控制系统中的应用实例。同时,详细探讨了安全增强(TLS/SSL)、性能优化(异步处理与背压控制)、测试监控及生产环境部署方案,为构建高可用、高性能的消息通信系统提供全面指导。附资源下载链接:[https://pan.quark.cn/s/14fcf913bae6](https://pan.quark.cn/s/14fcf913bae6)。
2425 0
|
SQL 前端开发 Java
深入理解 Spring Boot 项目中的分页与排序功能
本文深入讲解了在Spring Boot项目中实现分页与排序功能的完整流程。通过实际案例,从Service层接口设计到Mapper层SQL动态生成,再到Controller层参数传递及前端页面交互,逐一剖析每个环节的核心逻辑与实现细节。重点包括分页计算、排序参数校验、动态SQL处理以及前后端联动,确保数据展示高效且安全。适合希望掌握分页排序实现原理的开发者参考学习。
836 4

热门文章

最新文章