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;@Deprecatedprivate 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.*/@Deprecatedpublic 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.*/@Deprecatedpublic 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.javapublic 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 {@Beanpublic 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;}@Overridepublic int getOrder() {return LOAD_BALANCER_CLIENT_FILTER_ORDER;}@Overridepublic 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);}}@Overrideprotected 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 {@Beanpublic 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;@Deprecatedprivate 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.*/@Deprecatedpublic 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.*/@Deprecatedpublic 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.javapublic 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 {@Beanpublic 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";@Overridepublic 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";@Beanpublic RequestInterceptor requestInterceptor() {return new RequestInterceptor() {@Overridepublic void apply(RequestTemplate requestTemplate) {// 从当前请求的 Header 中获取 tokenServletRequestAttributes 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.rhkb.cn/news/314714.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

VSCode搭建内核源码阅读开发环境

0. 参考链接 使用VSCode进行linux内核代码阅读和开发_vscode阅读linux内核-CSDN博客 Ubuntu下的内核编译&#xff08;打造最精确的编译步骤&#xff09;_ubuntu 内核编译-CSDN博客 【Linux】&#xff08;Ubuntu&#xff09;内核编译 && 镜像制作_ubuntu 内核编译-CS…

Ubuntu部署jmeter与ant

为了整合接口自动化的持续集成工具&#xff0c;我将jmeter与ant都部署在了Jenkins容器中&#xff0c;并配置了build.xml 一、ubuntu部署jdk 1&#xff1a;先下载jdk-8u74-linux-x64.tar.gz&#xff0c;上传到服务器&#xff0c;这里上传文件用到了ubuntu 下的 lrzsz。 ubunt…

基于jenkins+docker实现CI/CD实践

项目简介 利用 Jenkins、Docker、SonarQube 和 Harbor 技术&#xff0c;搭建一个完整的 CI/CD 管道&#xff0c;实现持续集成、持续交付和持续部署的流程。通过自动化构建、测试、代码质量检查和容器化部署&#xff0c;将开发人员从繁琐的手动操作中解放出来&#xff0c;提高团…

SQLite运行时可加载扩展(三十五)

返回&#xff1a;SQLite—系列文章目录 上一篇:SQLite轻量级会话扩展&#xff08;三十四&#xff09; 下一篇:SQLite的DBSTAT 虚拟表&#xff08;三十六) 1. 概述 SQLite 能够在运行时加载扩展&#xff08;包括新的应用程序定义的 SQL 函数、整理序列、虚拟表和 VFS&…

【深度学习】烟雾和火焰数据集,野外数据集,超大量数据集,目标检测,YOLOv5

标注了2w张数据集&#xff0c;是目标检测yolo格式的&#xff0c;有火焰、烟雾两个目标&#xff0c;下图是训练时候的样子&#xff1a; 训练方法看这里&#xff1a; https://qq742971636.blog.csdn.net/article/details/138097481 数据集介绍 都是博主辛苦整理和标注的&…

C++必修:类与对象(一)

✨✨ 欢迎大家来到贝蒂大讲堂✨✨ &#x1f388;&#x1f388;养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; 所属专栏&#xff1a;C学习 贝蒂的主页&#xff1a;Betty’s blog 1. 面向过程与面向对象 1.1. 面向过程 我们之前学习的C语言就是一种面向过程的语…

SVN小乌龟汉化问题

1.首先确认中文语言包和SVN版本需要一致&#xff08;点击右键 选择最后一个选项即可查看&#xff09; 官网链接 点击这个官网链接可以下载对应版本的中文包 2.下载好之后直接无脑下一步安装即可 3.如果还是没有中文&#xff0c;找到这个文件夹&#xff0c;把里面的内容全部删…

【css】select实现placeholder效果

场景&#xff1a;使用select下拉选择框的时候&#xff0c;需要像其他控件一样提示默认信息。 问题&#xff1a;表单控件select没有placeholder属性。 解决方案&#xff1a;通过css实现&#xff0c;不需要js <style>select > option[disabled]{ color:#999;cursor: n…

VUE3 ref,props,生命周期

1.--ref属性 1.1代码 1.1.1子表 <template><div class"person"><h1>中国</h1><h2 ref"title2">北京</h2><h3>尚硅谷</h3><button click"showLog">点我输出h2这个元素</button>&l…

【软测学习笔记】Day01

&#x1f31f;博主主页&#xff1a;我是一只海绵派大星 &#x1f4da;专栏分类&#xff1a;前端 &#x1f4da;参考教程&#xff1a;黑马教程❤️感谢大家点赞&#x1f44d;收藏⭐评论✍️ 目录 一、测试介绍 1、什么是软件测试&#xff1f; 2、测试主流技能 二、测试常用分…

unity cinemachine相机 (案例 跟随角色移动)

安装相机包 打开包管理工具 在 unity registry 搜索cinemachine 会在maincamera中生成一个组件cinemachineBrain 只能通过虚拟相机操控 主相机 虚拟相机的参数 案例 1.固定相机效果 位置 在固定的地方 默认的模式 2.相机跟随人物效果 焦距设置 20 跟随设置 把playere…

Django框架之python后端框架介绍

一、网络框架及MVC、MTV模型 1、网络框架 网络框架&#xff08;Web framework&#xff09;是一种软件框架&#xff0c;用于帮助开发人员构建Web应用程序和Web服务。它提供了一系列预先编写好的代码和工具&#xff0c;以简化开发过程并提高开发效率。网络框架通常包括以下功能…

Web前端框架/库/工具

前言 俗话说&#xff1a;前端从步枪&#xff08;原生js&#xff09;到了半自动武器&#xff08;jQuery&#xff09;并进化为全自动武器&#xff08;三大框架&#xff08;angular&#xff0c;react&#xff0c;vue及其生态链&#xff09;&#xff09;。 常说工欲善其事必先利其…

python作业 切片逆转

题目&#xff1a; &#xff08;反转显示一个整数&#xff09;编写下面的函数&#xff0c;反向显示一个整数。 列如&#xff1a;reserse(3456)。编写一个测试程序&#xff0c;提示用户输入一个整数&#xff0c;然后显示它的反向数。 第一步定义一个函数&#xff1a; def rev…

AUTOSAR-SD篇

1 概述 服务发现模块的主要任务是管理在车内通信中被称为服务的功能实体的可用性&#xff0c;以及控制事件消息的发送行为。只允许向需要这些事件消息的接收器发送事件消息&#xff08;发布/订阅&#xff09;。 这里描述的解决方案也被称为SOME/IP-SD&#xff08;基于IP -服务发…

前端css中keyframes(关键帧)的简单使用

前端css中keyframes的使用 一、前言二、例子&#xff08;一&#xff09;、例子源码1&#xff08;二&#xff09;、源码1运行效果1.视频效果2.截图效果 三、结语四、定位日期 一、前言 关键帧keyframes是css动画的一种&#xff0c;主要用于定义动画过程中某一阶段的样式变化&am…

【STM32+HAL】读取电池电量

一、准备工作 有关CUBEMX的初始化配置&#xff0c;参见我的另一篇blog&#xff1a;【STM32HAL】CUBEMX初始化配置 有关定时器触发ADC模式配置&#xff0c;详见【STM32HAL】ADC采集波形实现 有关软件触发ADC模式配置&#xff0c;详见【STM32HAL】三轴按键PS2摇杆 二、所用工具…

Bytebase 2.16.0 - 支持 Oracle 和 SQL Server DML 变更的事前备份

&#x1f680; 新功能 支持 Oracle 和 SQL Server DML 变更的事前备份。 支持在 SQL 编辑器中显示存储过程和函数。 支持兼容 TDSQL 的 MySQL 和 PostgreSQL 版本。 支持把数据库密码存储在 AWS Secrets Manager 和 GCP Secret Manager。 支持通过 IAM 连接到 Google Clou…

VirtualBox7.0.16的蓝屏大坑与ssh登陆ubuntu虚拟机的办法

背景&#xff1a; 安装了最新版的VirtualBox&#xff0c;装了ubuntu系统&#xff0c;在win10下通过ssh死活无法与ubuntu进行正常登陆控制。 然后开始了踩坑。 问题1&#xff1a;ssh登陆失败&#xff0c;但是主机能ping通ubuntu&#xff0c;反过来也能ping通&#xff0c;网络…

线性代数基础1向量

1、向量是什么 1.1、向量的定义 在数学中&#xff0c;向量&#xff08;也称为欧几里得向量、几何向量、矢量&#xff09;&#xff0c;指具有大小和方向的量。它可以形象化地表示为带箭头的线段。箭头所指&#xff1a;代表向量的方向&#xff1b;线段长度&#xff1a;代表向量的…