自定义loadbalance实现feignclient的自定义路由

自定义loadbalance实现feignclient的自定义路由

项目背景

服务A有多个同事同时开发,每个同事都在dev或者test环境发布自己的代码,注册到注册中心有好几个(本文nacos为例),这时候调用feign可能会导致请求到不同分支的服务上面,会出现一些问题,本文重点在于解决该问题

实操

解决方案

/*** @author authorZhao* @since 2023-08-03*/
@EnableConfigurationProperties(LoadBalancerProperties.class)
public class LoadBalanceConfig{@Bean@ConditionalOnMissingBeanpublic ReactorLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(Environment environment,LoadBalancerClientFactory loadBalancerClientFactory) {String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);return new MyRoundRobinLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);}
}
//@Configuration(proxyBeanMethods = false)
//@LoadBalancerClients(defaultConfiguration = LoadBalanceConfig.class) 全局配置
//@LoadBalancerClient(value = "user-center-service",configuration = LoadBalanceConfig.class) //单个配置
public class LoadBalance {}
/*** A Round-Robin-based implementation of {@link ReactorServiceInstanceLoadBalancer}.** @author Spencer Gibb* @author Olga Maciaszek-Sharma* @author Zhuozhi JI*/
public class MyRoundRobinLoadBalancer implements ReactorServiceInstanceLoadBalancer {private static final Log log = LogFactory.getLog(CubeRoundRobinLoadBalancer.class);final AtomicInteger position;final String serviceId;ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;/*** @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 CubeRoundRobinLoadBalancer(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 CubeRoundRobinLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider,String serviceId, int seedPosition) {this.serviceId = serviceId;this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;this.position = new AtomicInteger(seedPosition);}@SuppressWarnings("rawtypes")@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) {ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider.getIfAvailable(NoopServiceInstanceListSupplier::new);return supplier.get(request).next().map(serviceInstances -> processInstanceResponse(supplier, serviceInstances));}private Response<ServiceInstance> processInstanceResponse(ServiceInstanceListSupplier supplier,List<ServiceInstance> serviceInstances) {Response<ServiceInstance> serviceInstanceResponse = getInstanceResponse(serviceInstances);if (supplier instanceof SelectedInstanceCallback && serviceInstanceResponse.hasServer()) {((SelectedInstanceCallback) supplier).selectedServiceInstance(serviceInstanceResponse.getServer());}return serviceInstanceResponse;}private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances) {for (ServiceInstance instance : instances) {if(instance instanceof NacosServiceInstance nacosServiceInstance){//项目注册的时候在配置一个元数据,后面可以根据当前上下文拿到当前tag,进行匹配,默认使用base分支String s = instance.getMetadata().get("feature-tag");if("base".equals(s)){return new DefaultResponse(nacosServiceInstance);}}}if (instances.isEmpty()) {if (log.isWarnEnabled()) {log.warn("No servers available for service: " + serviceId);}return new EmptyResponse();}// Ignore the sign bit, this allows pos to loop sequentially from 0 to// Integer.MAX_VALUEint pos = this.position.incrementAndGet() & Integer.MAX_VALUE;ServiceInstance instance = instances.get(pos % instances.size());return new DefaultResponse(instance);}}

loadbalance执行过程

调用流程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Lf3NGlrZ-1692865252643)(img/image-20230824160138272.png)]

feign.SynchronousMethodHandler#executeAndDecode
->feign.Client#execute
->FeignBlockingLoadBalancerClient#execute
public Response execute(Request request, Request.Options options) throws IOException {final URI originalUri = URI.create(request.url());String serviceId = originalUri.getHost();Assert.state(serviceId != null, "Request URI does not contain a valid hostname: " + originalUri);String hint = getHint(serviceId);DefaultRequest<RequestDataContext> lbRequest = new DefaultRequest<>(new RequestDataContext(buildRequestData(request), hint));Set<LoadBalancerLifecycle> supportedLifecycleProcessors = LoadBalancerLifecycleValidator.getSupportedLifecycleProcessors(//loadBalancerClientFactory是NamedContextFactory的子类 容器map,刷新user-center-service子容器loadBalancerClientFactory.getInstances(serviceId, LoadBalancerLifecycle.class),RequestDataContext.class, ResponseData.class, ServiceInstance.class);supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStart(lbRequest));//根据serviceId拿到ReactiveLoadBalancer,执行choose方法,然后到了我们的方法ServiceInstance instance = loadBalancerClient.choose(serviceId, lbRequest);org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse = new DefaultResponse(instance);if (instance == null) {String message = "Load balancer does not contain an instance for the service " + serviceId;if (LOG.isWarnEnabled()) {LOG.warn(message);}supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onComplete(new CompletionContext<ResponseData, ServiceInstance, RequestDataContext>(CompletionContext.Status.DISCARD, lbRequest, lbResponse)));return Response.builder().request(request).status(HttpStatus.SERVICE_UNAVAILABLE.value()).body(message, StandardCharsets.UTF_8).build();}String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri).toString();Request newRequest = buildRequest(request, reconstructedUrl);LoadBalancerProperties loadBalancerProperties = loadBalancerClientFactory.getProperties(serviceId);return executeWithLoadBalancerLifecycleProcessing(delegate, options, newRequest, lbRequest, lbResponse,supportedLifecycleProcessors, loadBalancerProperties.isUseRawStatusCodeInResponseData());}

在这里插入图片描述

后面MyRoundRobinLoadBalancer其实是抄袭RoundRobinLoadBalancer的实现,默认就是轮训

本文为原创,转载请申明

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

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

相关文章

React(7)

1.React Hooks 使用hooks理由 1. 高阶组件为了复用&#xff0c;导致代码层级复杂 2. 生命周期的复杂 3. 写成functional组件,无状态组件 &#xff0c;因为需要状态&#xff0c;又改成了class,成本高 1.1 useState useState();括号里面处的是初始值&#xff1b;返回的是一个…

【算法系列 | 7】深入解析查找算法之—布隆过滤器

序言 心若有阳光&#xff0c;你便会看见这个世界有那么多美好值得期待和向往。 决定开一个算法专栏&#xff0c;希望能帮助大家很好的了解算法。主要深入解析每个算法&#xff0c;从概念到示例。 我们一起努力&#xff0c;成为更好的自己&#xff01; 今天第3讲&#xff0c;讲一…

stm32之8.中断

&#xff08;Exceptions&#xff09;异常是导致程序流更改的事件&#xff0c;发生这种情况&#xff0c;处理器将挂起当前执行的任务&#xff0c;并执行程序的一部分&#xff0c;称之为异常处理函数。在完成异常处理程序的执行之后&#xff0c;处理器将恢复正常的程序执行&#…

python+TensorFlow实现人脸识别智能小程序的项目(包含TensorFlow版本与Pytorch版本)

pythonTensorFlow实现人脸识别智能小程序的项目&#xff08;包含TensorFlow版本与Pytorch版本&#xff09; 一&#xff1a;TensorFlow基础知识内容部分&#xff08;简明扼要&#xff0c;快速适应&#xff09;1、下载Cifar10数据集&#xff0c;并进行解压缩处理2、将Cifar10数据…

WebSocket详解以及应用

&#x1f61c;作 者&#xff1a;是江迪呀✒️本文关键词&#xff1a;websocket、网络、长连接、前端☀️每日 一言&#xff1a;任何一个你不喜欢而又离不开的地方&#xff0c;任何一种你不喜欢而又无法摆脱的生活&#xff0c;都是监狱&#xff01; 一、前言 我们在…

C#-集合小例子

目录 背景&#xff1a; 过程: 1.添加1-100数: 2.求和: 3.平均值: 4.代码:​ 总结: 背景&#xff1a; 往集合里面添加100个数&#xff0c;首先得有ArrayList导入命名空间&#xff0c;这个例子分为3步&#xff0c;1.添加1-100个数2.进行1-100之间的总和3.求总和的平均值&…

如何把本地项目上传github

一、在gitHub上创建新项目 【1】点击添加&#xff08;&#xff09;-->New repository 【2】填写新项目的配置项 Repository name&#xff1a;项目名称 Description &#xff1a;项目的描述 Choose a license&#xff1a;license 【3】点击确定&#xff0c;项目已在githu…

数据结构数组栈的实现

Hello&#xff0c;今天我们来实现一下数组栈&#xff0c;学完这个我们又更进一步了。 一、栈 栈的概念 栈是一种特殊的线性表&#xff0c;它只允许在固定的一端进行插入和删除元素的操作。 进行数据的插入和删除只在栈顶实现&#xff0c;另一端就是栈底。 栈的元素是后进先出。…

四川玖璨电商:2023怎样运营短视频?

​短视频的兴起和流行让越来越多的人关注和运营短视频号。如何运营短视频号&#xff0c;吸引更多的观众和粉丝&#xff1f;下面四川玖璨电商小编将介绍几个关键点。 首先&#xff0c;确定短视频的定位和主题非常重要。根据自己的兴趣和特长&#xff0c;确定一个独特的主题&…

Linux学习-keepalived实现LVS高可用

Keepalived实现LVS高可用 环境准备 环境说明&#xff1a;LVS-DR模式 client1&#xff1a;eth0->192.168.88.10 lvs1&#xff1a;eth0->192.168.88.5 lvs2&#xff1a;eth0->192.168.88.6 web1&#xff1a;eth0->192.168.88.100 web2&#xff1a;eth0->192.16…

Python最新面试题汇总及答案

一、基础部分 1、什么是Python&#xff1f;为什么它会如此流行&#xff1f;Python是一种解释的、高级的、通用的编程语言。Python的设计理念是通过使用必要的空格与空行&#xff0c;增强代码的可读性。它之所以受欢迎&#xff0c;就是因为它具有简单易用的语法 2、为什么Pytho…

【算法系列总结之分组循环篇】

【算法系列总结之分组循环篇】 分组循环1446.连续字符1869.哪种连续子字符串更长1957.删除字符使字符串变好2038.如果相邻两个颜色均相同则删除当前颜色1759.统计同质子字符串的数目2110.股票平滑下跌阶段的数目1578.使绳子变成彩色的最短时间1839.所有元音按顺序排布的最长子字…

自动驾驶——最优控制算法(LQR)工程化总结

时隔一年&#xff0c;从写下第一篇博文自动驾驶-LQR工程实现&#xff08;调研&#xff09;&#xff0c;到近段时间&#xff0c;真正在我们的控制器上运行最优控制算法&#xff08;LQR&#xff09;&#xff0c;一步一个脚印&#xff0c;从开始只是知道其“控制理论”的阶段、再到…

Diffusion Models for Image Restoration and Enhancement – A Comprehensive Survey

图像恢复与增强的扩散模型综述 论文链接&#xff1a;https://arxiv.org/abs/2308.09388 项目地址&#xff1a;https://github.com/lixinustc/Awesome-diffusion-model-for-image-processing/ Abstract 图像恢复(IR)一直是低水平视觉领域不可或缺的一项具有挑战性的任务&…

vue helloworld.vue 点击按钮弹出 dialog,并给dialog传值

1 DataAnalysisVue.Vue -->应该组件文件名和 name: 的名字一致 <template><div><el-dialog :title"dataAnalysisMsg" :visible.sync"dataAnalysisvalue" :before-close"handleClose"><span>{{ dataAnalysisMsg }}&l…

Oracle 19c 启动和关闭实例保存PDB状态

简介&#xff1a; 十年以上 MySQL Oracle DBA从业者&#xff0c;MySQL 5.7 OCP&#xff0c; 微信号: jinjushuke 当前有一个PDB 打开模式为READ WRITE [oracleDGMOGGM19C ~]$ sql sys192.168.3.107:1521/pdb1 as sysdba SQLcl: Release 19.1 Production on Wed Aug 23 10:19:…

excel中如果A列中某项有多条记录,针对A列中相同的项,将B列值进行相加合并统计

excel中如果A列中某项有多条记录&#xff0c;针对A列中相同的项&#xff0c;将B列值进行相加合并统计。注意&#xff1a;B列的数据类型要为数字 如&#xff1a; 实现方法&#xff1a; C1、D1中分别输入公式&#xff0c;然后下拉 IF(COUNTIF($A$1:A1,A1)1, A1,"") …

C++:构造方法(函数);拷贝(复制)构造函数:浅拷贝、深拷贝;析构函数。

1.构造方法(函数) 构造方法是一种特殊的成员方法&#xff0c;与其他成员方法不同: 构造方法的名字必须与类名相同&#xff1b; 无类型、可有参数、可重载 会自动生成&#xff0c;可自定义 一般形式:类名(形参)&#xff1b; 例: Stu(int age); 当用户没自定义构造方法时&…

光伏发电+boost+储能+双向dcdc+并网逆变器控制(低压用户型电能路由器仿真模型)【含个人笔记+建模参考】

MATALB代码链接&#xff1a;光伏发电boost十储能十双向dcdc十并网逆变器 个人笔记与建模参考请私信发送 包含Boost、Buck-boost双向DCDC、并网逆变器三大控制部分 boost电路应用mppt&#xff0c; 采用扰动观察法实现光能最大功率点跟踪 电流环的逆变器控制策略 双向dcdc储能系…

react导出、导入文件

导出文件&#xff1a; if (res) {let binaryData [];binaryData.push(res);let blobUrl ;blobUrl res;// let blobUrl window.URL.createObjectURL(new Blob(binaryData, { type: application / zip }));console.log(blobUrl);const eleLink document.createElement(a);el…