springcloud整合nacos实现相同版本实例相互调用

springcloud整合nacos实现相同版本实例相互调用

注: 本文为自己学习研究总结,仅供参考,若有侵权,请及时联系本人

业务场景

有时候一些新的业务或者修改后的功能只开放给部分人访问,那么可以新老版本都部署,对于大多数人访问老版本,部分人访问新版本。部分人请求的时候,http请求header添加特定的version值,结合nacos的服务元数据进行塞选服务实例,从而实现不同人访问相同的功能,对应不同的版本。

基础理论

(1)基于feign进行远程方法调用,首先FeignBlockingLoadBalancerClient会根据url中的serviceId,交给LoadBalancerClient#choose()方法拉取服务列表并且基于负载均衡算法选择一个服务实例,最后重构Uri发起请求

(2)RoundRobinLoadbalancer(轮询,springcloudloadbalance默认负载均衡实现,还有一个是随机负载均衡)为例,ServiceInstanceListSupplier#get()用于拉取服务实例,getInstanceResponse()用于负载均衡选择某个实例

coding

demo如下:

java 复制代码
import com.google.common.collect.Lists;
import com.test.server.util.GreyThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.DelegatingServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Slf4j
public class SameVersionServiceInstanceListSupplier extends DelegatingServiceInstanceListSupplier {
    private final String VERSION = "version";

    public SameVersionServiceInstanceListSupplier(ServiceInstanceListSupplier delegate) {
        super(delegate);
    }

    @Override
    public Flux<List<ServiceInstance>> get() {
        ServiceInstanceListSupplier delegate1 = getDelegate();
        Flux<List<ServiceInstance>> listFlux = delegate1.get();
        Flux<List<ServiceInstance>> map = listFlux.map(this::filteredByVersion);
        return map;
    }

    /**
     * 根据version进行过滤
     * @param serviceInstances
     * @return
     */
    private List<ServiceInstance> filteredByVersion(List<ServiceInstance> serviceInstances) {
        List<ServiceInstance> filteredInstances = new ArrayList<>();
        for (ServiceInstance serviceInstance : serviceInstances) {
            String instanceVersion = getVersion(serviceInstance);
            if (GreyThreadLocalUtils.getVersion().equalsIgnoreCase(instanceVersion)) {
                filteredInstances.add(serviceInstance);
            }
        }
        if (filteredInstances.size() > 0) {
            return filteredInstances;
        }
        return Lists.newArrayList();
    }

    /**
     * 从元数据获取version值
     * @param serviceInstance
     * @return
     */
    private String getVersion(ServiceInstance serviceInstance) {
        Map<String, String> metadata = serviceInstance.getMetadata();
        if (metadata != null) {
            return metadata.get(VERSION);
        }
        return null;
    }
}
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.loadbalancer.support.SimpleObjectProvider;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
@Configuration(proxyBeanMethods = false)
public class LoadBalanceConfig {

    /**
     * 支持的服务实例
     * @param context
     * @return
     */
    @Bean
    public ServiceInstanceListSupplier serviceInstanceListSupplier(ConfigurableApplicationContext context) {
        ServiceInstanceListSupplier supplier = ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient().withCaching().build(context);
        return new SameVersionServiceInstanceListSupplier(supplier);
    }

    /**
     * 负载均衡方式
     * @param environment
     * @param serviceInstanceListSupplier
     * @return
     */
    @Bean
    public ReactorLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(Environment environment, ServiceInstanceListSupplier serviceInstanceListSupplier) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RoundRobinLoadBalancer(new SimpleObjectProvider<>(serviceInstanceListSupplier), name);
    }
}
/**
 * 注入了spring容器
 */
@Configuration(proxyBeanMethods = false)
@LoadBalancerClients(defaultConfiguration = LoadBalanceConfig.class)
@AutoConfigureBefore({ ReactorLoadBalancerClientAutoConfiguration.class,
        LoadBalancerBeanPostProcessorAutoConfiguration.class })
public class LoadBalanceAutoConfiguration {
}

参考资料

(1) https://mp.weixin.qq.com/s/rsRGMRiRb0atKclPl2K1zg

(2) 黑马程序员 java黑马商城项目微服务实战开发视频讲解

相关推荐
跳跳的向阳花18 分钟前
03-03、SpringCloud第三章,负载均衡Ribbon和Feign
spring cloud·ribbon·负载均衡
天天扭码16 小时前
五天SpringCloud计划——DAY1之mybatis-plus的使用
java·spring cloud·mybatis
luckywuxn1 天前
Spring Cloud Alibaba、Spring Cloud 与 Spring Boot各版本的对应关系
spring boot·spring·spring cloud
wclass-zhengge2 天前
SpringCloud篇(服务网关 - GateWay)
spring boot·spring cloud·gateway
荆州克莱2 天前
Redis | Redis常用命令及示例总结(API)
spring boot·spring·spring cloud·css3·技术
RainbowSea2 天前
5. Spring Cloud OpenFeign 声明式 WebService 客户端的超详细使用
java·spring·spring cloud
听潮阁2 天前
【SpringCloud详细教程】-02-微服务环境搭建
spring·spring cloud·微服务
阿维的博客日记2 天前
java八股-SpringCloud微服务-Eureka理论
spring cloud·eureka·nacos
跳跳的向阳花2 天前
03-02、SpringCloud第二章,Eureka服务的注册与发现
spring·spring cloud·eureka
泰山小张只吃荷园2 天前
快速入门消息队列MQ、RabbitMQ
java·spring boot·分布式·spring·spring cloud·rabbitmq·java-rabbitmq