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黑马商城项目微服务实战开发视频讲解

相关推荐
荆州克莱6 小时前
Golang的图形编程基础
spring boot·spring·spring cloud·css3·技术
sjsjsbbsbsn16 小时前
基于注解实现去重表消息防止重复消费
java·spring boot·分布式·spring cloud·java-rocketmq·java-rabbitmq
荆州克莱20 小时前
Golang的网络编程安全
spring boot·spring·spring cloud·css3·技术
拾忆,想起21 小时前
微服务入门:从零开始构建你的微服务架构
spring·spring cloud·微服务·架构
m0_5480497021 小时前
SpringCloud学习笔记【尚硅谷2024版】
笔记·学习·spring cloud
小扳1 天前
博客之星2024年度-技术总结:技术探险家小板的一年的征程
java·大数据·spring boot·elasticsearch·搜索引擎·spring cloud·微服务
晨的挥霍1 天前
spring cloud之gateway和JWT回顾
spring·spring cloud·gateway
weixin_SAG2 天前
14天学习微服务-->第2天:Spring Cloud深入与实践
学习·spring cloud·微服务
zzyh1234562 天前
搭建springcloud脚手架
后端·spring·spring cloud
Hello Dam2 天前
Jmeter 动态参数压力测试时间段预定接口
jmeter·spring cloud·springboot·压力测试