springcloud按版本发布微服务达到不停机更新的效果

本文基于以下环境完成

  • spring-boot 2.3.2.RELEASE
  • spring-cloud Hoxton.SR9
  • spring-cloud-alibaba 2.2.6.RELEASE
  • spring-cloud-starter-gateway 2.2.6.RELEASE
  • spring-cloud-starter-loadbalancer 2.2.6.RELEASE
  • nacos 2.0.3

一、思路

实现思路:
前端项目在请求后端接口时,携带一个版本号version,网关gateway在接收到这个version后,根据version的值去选择对应的微服务实例,服务之间的调用openfeign也通过版本号去选择对应的服务实例

举例:
每次更新项目时版本号递增,比如目前在使用的后端项目版本为1.0.0,那么前端携带的版本也是1.0.0,
当我们要更新项目时,后端新的版本为2.0.0 前端项目的版本也为2.0.0,如果用户没有刷新页面,那么还是携带旧的版本号1.0.0, 那么请求都会转发到后端1.0.0, 如果用户刷新页面,那么就会携带新版本号2.0.0,此时请求被转发后端2.0.0版本

实现方式:
排除自带的ribbon依赖

<exclusions>
    <exclusion>
        <groupId>org.springframework.cloud</groupId>
    </exclusion>
</exclusions>

引入spring-cloud-loadbalancer依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

spring-cloud-loadbalancer文档地址:点我跳转

配置微服务版本号

spring:
  cloud:
    nacos:
      discovery:
        metadata:
          version: 2.0.0

后续可以在nacos中修改
在这里插入图片描述

二 、重写网关的负载策略

2.1 重写轮训负载均衡

spring-cloud-loadbalancer默认的负载策略是轮训,实现类为org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer,我们主要看里面的choose和getInstanceResponse方法,在getInstanceResponse方法中传入ServiceInstance集合,然后从这个集合中选择一个合适的instance实例,那么我们只要在重写这个方法在里面添加版本的筛选
在这里插入图片描述那么我们再看一下这个类是如何实例化的,主要是org.springframework.cloud.loadbalancer.annotation.LoadBalancerClientConfiguration

在这里插入图片描述
注意@ConditionalOnMissingBean这个注解,只有当spring容器中没有ReactorLoadBalancer类型的bean时才会实例化。

我们新建一个VersionLoadBalancer类,跟RoundRobinLoadBalancer一样去实现ReactorServiceInstanceLoadBalancer接口(其实就是把他的代码copy过来,然后添加我们自定义的筛选条件)

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.loadbalancer.core.*;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.reactive.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.reactive.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.reactive.Request;
import org.springframework.cloud.client.loadbalancer.reactive.Response;

/**
 * {@link org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer}
 *
 * @Author 
 * @Date 2024/4/18 11:46
 * @Description
 **/
public class VersionLoadBalancer implements ReactorServiceInstanceLoadBalancer {

    private static final Log log = LogFactory.getLog(VersionLoadBalancer.class);

    private final AtomicInteger position;

    @Deprecated
    private ObjectProvider<ServiceInstanceSupplier> serviceInstanceSupplier;

    private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;

    private final String serviceId;

    /**
     * @param serviceId               id of the service for which to choose an instance
     * @param serviceInstanceSupplier a provider of {@link ServiceInstanceSupplier} that
     *                                will be used to get available instances
     * @deprecated Use {@link #VersionLoadBalancer(ObjectProvider, String)}} instead.
     */
    @Deprecated
    public VersionLoadBalancer(String serviceId,
                               ObjectProvider<ServiceInstanceSupplier> serviceInstanceSupplier) {
        this(serviceId, serviceInstanceSupplier, new Random().nextInt(1000));
    }

    /**
     * @param serviceInstanceListSupplierProvider a provider of
     *                                            {@link ServiceInstanceListSupplier} that will be used to get available instances
     * @param serviceId                           id of the service for which to choose an instance
     */
    public VersionLoadBalancer(
            ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider,
            String serviceId) {
        this(serviceInstanceListSupplierProvider, serviceId, new Random().nextInt(1000));
    }

    /**
     * @param serviceInstanceListSupplierProvider a provider of
     *                                            {@link ServiceInstanceListSupplier} that will be used to get available instances
     * @param serviceId                           id of the service for which to choose an instance
     * @param seedPosition                        Round Robin element position marker
     */
    public VersionLoadBalancer(
            ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider,
            String serviceId, int seedPosition) {
        this.serviceId = serviceId;
        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
        this.position = new AtomicInteger(seedPosition);
    }

    /**
     * @param serviceId               id of the service for which to choose an instance
     * @param serviceInstanceSupplier a provider of {@link ServiceInstanceSupplier} that
     *                                will be used to get available instances
     * @param seedPosition            Round Robin element position marker
     * @deprecated Use {@link #VersionLoadBalancer(ObjectProvider, String, int)}}
     * instead.
     */
    @Deprecated
    public VersionLoadBalancer(String serviceId,
                               ObjectProvider<ServiceInstanceSupplier> serviceInstanceSupplier,
                               int seedPosition) {
        this.serviceId = serviceId;
        this.serviceInstanceSupplier = serviceInstanceSupplier;
        this.position = new AtomicInteger(seedPosition);
    }

    @SuppressWarnings("all")
    @Override
    // see original
    // https://github.com/Netflix/ocelli/blob/master/ocelli-core/
    // src/main/java/netflix/ocelli/loadbalancer/RoundRobinLoadBalancer.java
    public Mono<Response<ServiceInstance>> choose(Request request) {
        HttpHeaders headers = (HttpHeaders) request.getContext();
        String requestVersion = headers.getFirst("version");
        // TODO: move supplier to Request?
        // Temporary conditional logic till deprecated members are removed.
        if (serviceInstanceListSupplierProvider != null) {
            ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider
                    .getIfAvailable(NoopServiceInstanceListSupplier::new);
            return supplier.get().next().map(m -> this.getInstanceResponse(m, requestVersion));
        }
        ServiceInstanceSupplier supplier = this.serviceInstanceSupplier
                .getIfAvailable(NoopServiceInstanceSupplier::new);
        return supplier.get().collectList().map(m -> this.getInstanceResponse(m, requestVersion));
    }

    @SuppressWarnings("deprecation")
    private Response<ServiceInstance> getInstanceResponse(
            List<ServiceInstance> instances, String requestVersion) {
        List<ServiceInstance> serviceInstances = this.filterInstance(instances, requestVersion);
        if (serviceInstances.isEmpty()) {
            log.warn("No servers available for service: " + this.serviceId + " ,request version: " + requestVersion);
            return new EmptyResponse();
        }
        // TODO: enforce order?
        int pos = Math.abs(this.position.incrementAndGet());

        ServiceInstance instance = serviceInstances.get(pos % serviceInstances.size());

        return new DefaultResponse(instance);
    }

    /**
     * 获取对应的版本
     *
     * @param instances
     * @param requestVersion
     * @return
     */
    private List<ServiceInstance> filterInstance(List<ServiceInstance> instances, String requestVersion) {
        if (StringUtils.isEmpty(requestVersion)) {
            return instances;
        }
        return instances.stream().filter(f -> requestVersion.equals(f.getMetadata().get("version"))).collect(Collectors.toList());
    }

}

然后新建一个配置类VersionLoadBalancerConfig,注意不能使用@Configuration

import com.demo.gateway.filter.VersionLoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * 注意: 这里不能使用@Configuration !!!
 * 参考 {@link org.springframework.cloud.loadbalancer.annotation.LoadBalancerClientConfiguration}
 *
 * @Author 
 * @Date 2024/4/18 11:50
 * @Description
 **/

public class VersionLoadBalancerConfig {

    @Bean
    public ReactorLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(
            Environment environment,
            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new VersionLoadBalancer(loadBalancerClientFactory.getLazyProvider(name,
                ServiceInstanceListSupplier.class), name);
    }

}

官方文档示例
在这里插入图片描述
然后在项目的启动类添加@LoadBalancerClients(defaultConfiguration = {VersionLoadBalancerConfig.class})

import com.demo.gateway.config.VersionLoadBalancerConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;

/**
 * @Author 
 * @Date 2022/10/10 16:38
 * @Description
 **/
@EnableDiscoveryClient
@SpringBootApplication
@LoadBalancerClients(defaultConfiguration = {VersionLoadBalancerConfig.class})
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

}

2.2 重写过滤器

此时运行项目发现碰到空指针异常,断点后发现是VersionLoadBalancer.choose方法里面request.getContext()是个null值,那么我们再看一下是在哪里调用了这个方法,主要是org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter
在这里插入图片描述在这里插入图片描述那么我们需要重写这个过滤器,在choose方法里面将我们http请求的header对象传递给VersionLoadBalancer,我们再看一下ReactiveLoadBalancerClientFilter是怎么初始化的,主要是org.springframework.cloud.gateway.config.GatewayReactiveLoadBalancerClientAutoConfiguration
在这里插入图片描述
那么我们就可以新建一个VersionLoadBalancerFilter去覆盖原来的ReactiveLoadBalancerClientFilter(如果直接新增一个过滤器那么原来的过滤器也会执行,还会有过滤器的执行顺序问题)

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerUriTools;
import org.springframework.cloud.client.loadbalancer.reactive.DefaultRequest;
import org.springframework.cloud.client.loadbalancer.reactive.Request;
import org.springframework.cloud.client.loadbalancer.reactive.Response;
import org.springframework.cloud.gateway.config.LoadBalancerProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter;
import org.springframework.cloud.gateway.support.DelegatingServiceInstance;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;

/**
 * 参考 {@link ReactiveLoadBalancerClientFilter}
 * @Author SYLIANG
 * @Date 2024/4/19 10:48
 * @Description
 **/
public class VersionLoadBalancerFilter extends ReactiveLoadBalancerClientFilter implements GlobalFilter, Ordered {

    private static final Log log = LogFactory.getLog(VersionLoadBalancerFilter.class);

    private static final int LOAD_BALANCER_CLIENT_FILTER_ORDER = 10250;

    private final LoadBalancerClientFactory clientFactory;

    private LoadBalancerProperties properties;

    public VersionLoadBalancerFilter(LoadBalancerClientFactory clientFactory, LoadBalancerProperties properties) {
        super(clientFactory, properties);
        this.clientFactory = clientFactory;
        this.properties = properties;
    }

    @Override
    public int getOrder() {
        return LOAD_BALANCER_CLIENT_FILTER_ORDER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        URI url = (URI)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
        String schemePrefix = (String)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR);
        if (url != null && ("lb".equals(url.getScheme()) || "lb".equals(schemePrefix))) {
            ServerWebExchangeUtils.addOriginalRequestUrl(exchange, url);
            if (log.isTraceEnabled()) {
                log.trace(ReactiveLoadBalancerClientFilter.class.getSimpleName() + " url before: " + url);
            }

            return this.choose(exchange).doOnNext((response) -> {
                if (!response.hasServer()) {
                    throw NotFoundException.create(this.properties.isUse404(), "Unable to find instance for " + url.getHost());
                } else {
                    ServiceInstance retrievedInstance = (ServiceInstance)response.getServer();
                    URI uri = exchange.getRequest().getURI();
                    String overrideScheme = retrievedInstance.isSecure() ? "https" : "http";
                    if (schemePrefix != null) {
                        overrideScheme = url.getScheme();
                    }

                    DelegatingServiceInstance serviceInstance = new DelegatingServiceInstance(retrievedInstance, overrideScheme);
                    URI requestUrl = this.reconstructURI(serviceInstance, uri);
                    if (log.isTraceEnabled()) {
                        log.trace("LoadBalancerClientFilter url chosen: " + requestUrl);
                    }

                    exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, requestUrl);
                }
            }).then(chain.filter(exchange));
        } else {
            return chain.filter(exchange);
        }
    }

    @Override
    protected URI reconstructURI(ServiceInstance serviceInstance, URI original) {
        return LoadBalancerUriTools.reconstructURI(serviceInstance, original);
    }

    @SuppressWarnings("deprecation")
    private Mono<Response<ServiceInstance>> choose(ServerWebExchange exchange) {
        URI uri = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
        ReactorLoadBalancer<ServiceInstance> loadBalancer = this.clientFactory
                .getInstance(uri.getHost(), VersionLoadBalancer.class);
        if (loadBalancer == null) {
            throw new NotFoundException("No loadbalancer available for " + uri.getHost());
        } else {
            return loadBalancer.choose(this.createRequest(exchange));
        }
    }

    @SuppressWarnings("deprecation")
    private Request createRequest(ServerWebExchange exchange) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        Request<HttpHeaders> request = new DefaultRequest<>(headers);
        return request;
    }
}

注意choose方法里面的ReactorLoadBalancer loadBalancer = this.clientFactory.getInstance(uri.getHost(), VersionLoadBalancer.class); 这里不能直接new,否则轮训会失效

新建配置类VersionFilterConfiguration

import com.personnel.gateway.filter.VersionLoadBalancerFilter;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoadBalancer;
import org.springframework.cloud.gateway.config.GatewayLoadBalancerClientAutoConfiguration;
import org.springframework.cloud.gateway.config.LoadBalancerProperties;
import org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter;
import org.springframework.cloud.loadbalancer.config.LoadBalancerAutoConfiguration;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.DispatcherHandler;

/**
 * ReactiveLoadBalancerClientFilter过滤器的Request没有请求头信息
 * 参考 {@link org.springframework.cloud.gateway.config.GatewayReactiveLoadBalancerClientAutoConfiguration}
 *
 * @Author 
 * @Date 2024/4/22 15:56
 * @Description
 **/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({LoadBalancerClient.class, ReactiveLoadBalancer.class,
        LoadBalancerAutoConfiguration.class, DispatcherHandler.class})
@AutoConfigureBefore(GatewayLoadBalancerClientAutoConfiguration.class)
@AutoConfigureAfter(LoadBalancerAutoConfiguration.class)
@EnableConfigurationProperties(LoadBalancerProperties.class)
public class VersionFilterConfiguration {

    @Bean
    public ReactiveLoadBalancerClientFilter versionLoadBalancer(LoadBalancerClientFactory clientFactory,
                                                                LoadBalancerProperties properties) {
        return new VersionLoadBalancerFilter(clientFactory, properties);
    }

}

三、重写openfeign的负载策略

3.1 spring-cloud-loadbalancer负载

我们同样使用spring-cloud-loadbalancer作为负载均衡器,新建自定义负载策略VersionLoadBalancer类,注意这里面的版本号version通过spring-web的ServletRequestAttributes获取

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.reactive.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.reactive.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.reactive.Request;
import org.springframework.cloud.client.loadbalancer.reactive.Response;
import org.springframework.cloud.loadbalancer.core.*;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 *
 * 重写负载均衡策略: 通过版本选择服务实例
 * {@link RoundRobinLoadBalancer}
 *
 * @Author 
 * @Date 2024/4/18 11:46
 * @Description
 **/
public class VersionLoadBalancer implements ReactorServiceInstanceLoadBalancer {

    private static final Log log = LogFactory.getLog(VersionLoadBalancer.class);

    private final AtomicInteger position;

    @Deprecated
    private ObjectProvider<ServiceInstanceSupplier> serviceInstanceSupplier;

    private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;

    private final String serviceId;

    private final String version = "version";

    /**
     * @param serviceId               id of the service for which to choose an instance
     * @param serviceInstanceSupplier a provider of {@link ServiceInstanceSupplier} that
     *                                will be used to get available instances
     * @deprecated Use {@link #VersionLoadBalancer(ObjectProvider, String)}} instead.
     */
    @Deprecated
    public VersionLoadBalancer(String serviceId,
                               ObjectProvider<ServiceInstanceSupplier> serviceInstanceSupplier) {
        this(serviceId, serviceInstanceSupplier, new Random().nextInt(1000));
    }

    /**
     * @param serviceInstanceListSupplierProvider a provider of
     *                                            {@link ServiceInstanceListSupplier} that will be used to get available instances
     * @param serviceId                           id of the service for which to choose an instance
     */
    public VersionLoadBalancer(
            ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider,
            String serviceId) {
        this(serviceInstanceListSupplierProvider, serviceId, new Random().nextInt(1000));
    }

    /**
     * @param serviceInstanceListSupplierProvider a provider of
     *                                            {@link ServiceInstanceListSupplier} that will be used to get available instances
     * @param serviceId                           id of the service for which to choose an instance
     * @param seedPosition                        Round Robin element position marker
     */
    public VersionLoadBalancer(
            ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider,
            String serviceId, int seedPosition) {
        this.serviceId = serviceId;
        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
        this.position = new AtomicInteger(seedPosition);
    }

    /**
     * @param serviceId               id of the service for which to choose an instance
     * @param serviceInstanceSupplier a provider of {@link ServiceInstanceSupplier} that
     *                                will be used to get available instances
     * @param seedPosition            Round Robin element position marker
     * @deprecated Use {@link #VersionLoadBalancer(ObjectProvider, String, int)}}
     * instead.
     */
    @Deprecated
    public VersionLoadBalancer(String serviceId,
                               ObjectProvider<ServiceInstanceSupplier> serviceInstanceSupplier,
                               int seedPosition) {
        this.serviceId = serviceId;
        this.serviceInstanceSupplier = serviceInstanceSupplier;
        this.position = new AtomicInteger(seedPosition);
    }

    @SuppressWarnings("all")
    @Override
    // see original
    // https://github.com/Netflix/ocelli/blob/master/ocelli-core/
    // src/main/java/netflix/ocelli/loadbalancer/RoundRobinLoadBalancer.java
    public Mono<Response<ServiceInstance>> choose(Request request) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String requestVersion = requestAttributes.getRequest().getHeader(version);
        // TODO: move supplier to Request?
        // Temporary conditional logic till deprecated members are removed.
        if (serviceInstanceListSupplierProvider != null) {
            ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider
                    .getIfAvailable(NoopServiceInstanceListSupplier::new);
            return supplier.get().next().map(m -> this.getInstanceResponse(m, requestVersion));
        }
        ServiceInstanceSupplier supplier = this.serviceInstanceSupplier
                .getIfAvailable(NoopServiceInstanceSupplier::new);
        return supplier.get().collectList().map(m -> this.getInstanceResponse(m, requestVersion));
    }

    @SuppressWarnings("deprecation")
    private Response<ServiceInstance> getInstanceResponse(
            List<ServiceInstance> instances, String requestVersion) {
        List<ServiceInstance> serviceInstances = this.filterInstance(instances, requestVersion);
        if (serviceInstances.isEmpty()) {
            log.warn("No servers available for service: " + this.serviceId + " ,request version: " + requestVersion);
            return new EmptyResponse();
        }
        // TODO: enforce order?
        int pos = Math.abs(this.position.incrementAndGet());

        ServiceInstance instance = serviceInstances.get(pos % serviceInstances.size());

        return new DefaultResponse(instance);
    }

    /**
     * 获取对应的版本
     *
     * @param instances
     * @param requestVersion
     * @return
     */
    private List<ServiceInstance> filterInstance(List<ServiceInstance> instances, String requestVersion) {
        if (StringUtils.isEmpty(requestVersion)) {
            return instances;
        }
        return instances.stream().filter(f -> requestVersion.equals(f.getMetadata().get(version))).collect(Collectors.toList());
    }

}

新建配置类VersionLoadBalancerConfig

import com.personnel.common.load.VersionLoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * 注意: 这里不能使用@Configuration !!!
 * 参考 {@link org.springframework.cloud.loadbalancer.annotation.LoadBalancerClientConfiguration}
 *
 * @Author 
 * @Date 2024/4/18 11:50
 * @Description
 **/

public class VersionLoadBalancerConfig {

    @Bean
    public ReactorLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(
            Environment environment,
            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new VersionLoadBalancer(loadBalancerClientFactory.getLazyProvider(name,
                ServiceInstanceListSupplier.class), name);
    }

}

在启动类中添加@LoadBalancerClients(defaultConfiguration = {VersionLoadBalancerConfig.class})

3.2 ribbon负载

如果使用ribbon则使用以下配置

import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.google.common.base.Optional;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidanceRule;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.ArrayList;
import java.util.List;

/**
 * openfeign调用根据版本选择对应的实例
 * @Author 
 * @Date 2024/1/18 14:16
 * @Description
 **/
@Component
public class VersionReleaseRule extends ZoneAvoidanceRule {

    private final String version = "version";

    @Override
    public Server choose(Object key) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String requestVersion = requestAttributes.getRequest().getHeader(version);
        if (!StringUtils.isEmpty(requestVersion)) {
            List<Server> serverList = this.getLoadBalancer().getAllServers();
            List<Server> versionServers = new ArrayList<>();
            for (Server server : serverList) {
                NacosServer nacosServer = (NacosServer) server;
                if (requestVersion.equals(nacosServer.getMetadata().get(version))) {
                    versionServers.add(server);
                }
            }
            if (!CollectionUtils.isEmpty(versionServers)) {
                Optional<Server> serverOptional = this.getPredicate().chooseRoundRobinAfterFiltering(versionServers, key);
                return serverOptional.isPresent() ? serverOptional.get() : null;
            }
        }
        return super.choose(key);
    }
}

四、openfeign携带token

在openfeign调用时如果没有携带token则添加以下配置

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 *  openfeign请求添加token
 * @Author SYLIANG
 * @Date 2024/4/25 11:22
 * @Description
 **/
@Configuration
public class FeignClientInterceptorConfig {

    private final String authorization = "Authorization";

    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                // 从当前请求的 Header 中获取 token
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    String token = attributes.getRequest().getHeader(authorization);
                    if (token != null && !token.isEmpty()) {
                        // 添加 token 到请求头部
                        requestTemplate.header(authorization, token);
                    }
                }
            }
        };
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/579007.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

SVN--基本原理与使用(超详细)

目录 一、SVN概述二、SVN服务端软件安装三、SVN服务端配置四、SVN客户端软件安装与使用五、SVN三大指令六、SVN图标集与忽略功能6.1 图标集6.2 忽略功能 七、SVN版本回退八、SVN版本冲突九、SVN配置多仓库与权限控制9.1 配置多仓库9.2 权限控制 十、服务配置与管理十一、模拟真…

Java | Leetcode Java题解之第52题N皇后II

题目&#xff1a; 题解&#xff1a; class Solution {public int totalNQueens(int n) {Set<Integer> columns new HashSet<Integer>();Set<Integer> diagonals1 new HashSet<Integer>();Set<Integer> diagonals2 new HashSet<Integer>…

手写文本识别系统的最佳实践

手写文本识别系统的最佳实践 摘要IntroductionRelated WorkProposed HTR SystemConvolutional Backbone:Flattening Operation:Recurrent Head:CTC shortcut: Best Practices for a Handwritten Text Recognition System 摘要 手写文本识别在近年来随着深度学习及其应用的兴起…

文件夹惊变文件?揭秘原因及解决方案

在日常工作和生活中&#xff0c;电脑已经成为我们不可或缺的助手。然而&#xff0c;有时我们会遇到一些令人困惑的问题&#xff0c;比如&#xff0c;文件夹突然变成了文件。这听起来可能有些匪夷所思&#xff0c;但它确实会发生&#xff0c;而且给用户带来了不小的麻烦。当熟悉…

java-spring-mvc(知识点讲解-第一天)-欢迎各位大佬提建议

目录 &#x1f383;MVC定义 &#x1f9e8;创建工程 &#x1f3a8;SpringMVC处理请求 请求分类及处理方式 静态请求 处理静态前端页面方式 动态请求 处理动态前端页面方式 ⚙小试牛刀 &#x1f3c6;常见问题 &#x1f4cc;HTTP协议 超文本传输协议 请求 &#x1f383;MVC…

Web前端开发 小实训(二) 简易计算器

实训目的 学生能够使用函数完成简易计算器编写 操作步骤 1、请将加减乘除四个方法生成为以下函数&#xff0c;且有返回值 中文英语加法add减法subtract乘法multi除法division次幂pow()平方根sqrt() 提示&#xff1a; 除法中的除数不能为0&#xff01; 参考代码&#xff1…

在线培训考试系统在线考试功能注意事项

在线培训考试系统在线考试功能注意事项 考试前务必注意是否开启防切屏、摄像头监考等防作弊措施&#xff0c;系统一旦检测到触发了疑似作弊行为会立刻自动交卷&#xff0c;考试终止&#xff1b; 答题者准备好后&#xff0c;可点击“开始答题”按钮进入考试&#xff0c;注意考…

代码随想录第49天|121. 买卖股票的最佳时机 122.买卖股票的最佳时机II

121. 买卖股票的最佳时机 121. 买卖股票的最佳时机 - 力扣&#xff08;LeetCode&#xff09; 代码随想录 (programmercarl.com) 动态规划之 LeetCode&#xff1a;121.买卖股票的最佳时机1_哔哩哔哩_bilibili 给定一个数组 prices &#xff0c;它的第 i 个元素 prices[i] 表示一…

#C++里的引用#

目录 引用概念 定义引用类型 引用特性 常引用 传引用传参 传引用做返回值 1.引用概念 引用不是新定义一个变量&#xff0c;而是给已存在变量取了一个别名&#xff0c;编译器不会为引用变量开辟内存空间&#xff0c;它和它引用的变量共用同一块内存空间。 比如&#xff1a…

【AI】一文介绍索引增强生成RAG的原理和结构

今天向大家介绍一下关于RAG的一些知识和经验。 这里说的RAG可以理解为目前针对企业知识库问答等AI应用场景的解决方案,这个场景就是利用自然语言大模型LLM与用户自有的文件进行对话的能力。 【RAG的优势】 首先,讲一讲RAG的优势特征。 如果把AI想象成一个待上岗的人类助手,…

1、Flink DataStreamAPI 概述(上)

一、DataStream API 1、概述 1&#xff09;Flink程序剖析 1.Flink程序组成 a&#xff09;Flink程序基本组成 获取一个执行环境&#xff08;execution environment&#xff09;&#xff1b;加载/创建初始数据&#xff1b;指定数据相关的转换&#xff1b;指定计算结果的存储…

模型 AIPL(认知、兴趣、购买、忠诚)

系列文章 分享 模型&#xff0c;了解更多&#x1f449; 模型_思维模型目录。品牌营销的量化与链路化。 1 AIPL模型的应用 1.1 耐克如何利用AIPL模型来推广其运动鞋和服装产品? 耐克利用AIPL模型来推广其运动鞋和服装产品&#xff0c;具体如下&#xff1a; 认知&#xff08;…

为什么总说抖店做不好?做抖店需要注意这些问题,是不是都占了?

大家好&#xff0c;我是电商花花。 今天给大家总结了4个新手不注意又常犯的几个原因&#xff0c;这些建议都是我们做店这些年的实操经验&#xff0c;可以帮助大家做店自查&#xff0c;有责改之&#xff0c;无责加冕。 1、抖店核心是选品而不是玩法 很多新手在刚开始做店抖音小…

8K+/月!学习就业一把梭,祝贺誉天数通陈同学收获心仪offer !

大家好&#xff0c;我是誉天数通的陈同学。 在武汉&#xff0c;网络运维圈的人应该都会听过誉天的名字。作为华为的授权培训合作伙伴&#xff0c;誉天不仅提供专业全面的工程师培训&#xff0c;还以其独特的环境和氛围吸引着无数有志于在网络领域发展的朋友。 一年前的我&#…

用坐标与碰撞检测效果

用pygame碰撞检测子弹 与 子弹 格子检查是否在墙内 结果差不了多少 输出的是碰撞点坐标 在计算角色与强的距离是 你用了几条射线 2024/4/26 13:20:48 在代码中&#xff0c;用于计算角色与墙之间距离的部分是通过投射多条射线来实现的。具体来说&#xff0c;在循环中&#xf…

IDEA插件

POJO to JSON —— 实体转Json Smart Input —— 自动切换中英文 Translation —— 翻译 Maven Helper —— 依赖管理 .ignore —— 忽略提交文件 enum-quick-generate —— 枚举代码生成 粘贴到项目包下

前端更优雅的使用 jsonp

前端更优雅的使用 jsonp 背景&#xff1a;最近项目中又使用到了 jsonp 这一项跨域的技术&#xff0c;&#xff08;主要还是受同源策略影响&#xff09;&#xff0c;下面有为大家提供封装好的函数及对应使用示例&#xff0c;欢迎大家阅读理解 文章目录 前端更优雅的使用 jsonp同…

基于车载点云数据的城市道路特征目标提取与三维重构

作者&#xff1a;邓宇彤&#xff0c;李峰&#xff0c;周思齐等 来源&#xff1a;《北京工业大学学报》 编辑&#xff1a;东岸因为一点人工一点智能公众号 基于车载点云数据的城市道路特征目标提取与三维重构本研究旨在弥补现有研究在处理复杂环境和大数据量上的不足&#xf…

Qt设置可执行程序图标,并打包发布

一、设置图标 图标png转ico: https://www.toolhelper.cn/Image/ImageToIco设置可执行程序图标 修改可执行程序图标 添加一个rc文件,操作如下,记得后缀改为rc 打开logo.rc文件添加代码IDI_ICON1 ICON DISCARDABLE "logo.ico"在项目pro后缀名的文件中添加代码 RC_…

系统盘空间不足调优方式1-APPData/大文件清理

作者&#xff1a;私语茶馆 1.前言 Windows系统盘&#xff08;C盘&#xff09;很容易剩余空间不足&#xff0c;这种情况下会非常影响Windows系统的运行&#xff0c;系统盘约束非常多&#xff0c;不方便在线扩容&#xff0c;因此规划和利用好系统盘是保障整体运行效率的关键。包…
最新文章