2.Feign使用、上下文隔离及源码阅读

目录

  • 概述
  • 使用
    • 配置
      • pom.xml
      • feign 接口编写
      • controller
    • 测试
    • 降级处理
      • pom.xml
      • application.yml
      • 代码
  • Feign如何初始化及调用源码阅读
    • 初始化
    • 调用
  • feign的上下文隔离机制
    • 源码
  • 结束

概述

阅读此文,可以知晓 feign 使用、上下文隔离及源码阅读。源码涉及两方面:feign如何初始化及如何调用。

使用

配置

  • pom.xm 配置 jar 包
  • 启动类添加注解 @EnableFeignClients
  • feign 接口编写

pom.xml

增加以下两个 jar

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency><dependency><groupId>io.github.openfeign</groupId><artifactId>feign-httpclient</artifactId>
</dependency>

feign 接口编写

package com.fun.ms.feign;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;@FeignClient("nacos-provider")
public interface OpenFeignProviderControllerFeignClient {@GetMapping("/hello/{id}")String echo(@PathVariable String id);
}

controller

controller 中使用 feign 调用。

@Autowired
private OpenFeignProviderControllerFeignClient feignClient;@GetMapping("/hello/feign/{id}")
public String echoFeign(@PathVariable String id) {return feignClient.echo(id);
}

测试

测试如下:
http://localhost:9060/hello/feign/helloword
在这里插入图片描述

降级处理

官方文档

**注意:**以下
在这里插入图片描述
测试接口:
http://localhost:9060/hello/feign/helloword

pom.xml

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId><version>2.2.10.RELEASE</version>
</dependency>

application.yml

feign:circuitbreaker:enabled: true

代码

feign 接口

@FeignClient(value = "nacos-provider", fallback = OpenFeignProviderControllerFeignClientFallback.class)
public interface OpenFeignProviderControllerFeignClient {@GetMapping("/hello/{id}")String echo(@PathVariable String id);
}

fallback

@Component
public class OpenFeignProviderControllerFeignClientFallback implements OpenFeignProviderControllerFeignClient {@Overridepublic String echo(String id) {return "Fallback receive args: id=" + id + ",date:"+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());}
}

测试 如下
在这里插入图片描述

Feign如何初始化及调用源码阅读

初始化

初始化关键要明白以下两点:

  • FeignClientsRegistrar ImportBeanDefinitionRegistrar 如何注入 @FeignClient
  • 如何动态代理生成对象 FeignClientFactoryBean

关键切入点

org.springframework.cloud.openfeign.EnableFeignClients
在这里插入图片描述

断点关键处如下:

org.springframework.cloud.openfeign.FeignClientsRegistrar#registerBeanDefinitions
org.springframework.cloud.openfeign.FeignClientsRegistrar#registerFeignClient
org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#scanCandidateComponents
org.springframework.cloud.openfeign.FeignClientsRegistrar#registerOptionsBeanDefinition
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#obtainFromSupplier
org.springframework.cloud.openfeign.FeignClientFactoryBean#getObject
org.springframework.cloud.openfeign.FeignClientFactoryBean#loadBalance
org.springframework.cloud.openfeign.FeignClientFactoryBean#get
org.springframework.cloud.openfeign.DefaultTargeter#target
feign.ReflectiveFeign#newInstance
feign.InvocationHandlerFactory.Default#create

关键:feign.ReflectiveFeign#newInstance,动态代理
在这里插入图片描述

调用

关键地方如下:
在这里插入图片描述

feign.ReflectiveFeign.FeignInvocationHandler#invoke
在这里插入图片描述

feign的上下文隔离机制

理解 feign 的上下文隔离机制,有助于我们对 feign 的使用有更深的理解。

源码

关键断点设置如下:

org.springframework.cloud.openfeign.FeignClientFactoryBean#getTarget
org.springframework.cloud.openfeign.FeignAutoConfiguration#feignContext
org.springframework.cloud.openfeign.FeignClientFactoryBean#feign
org.springframework.cloud.openfeign.FeignClientFactoryBean#get
org.springframework.cloud.context.named.NamedContextFactory#getContext
org.springframework.cloud.context.named.NamedContextFactory#createContext

几个关键点

org.springframework.cloud.openfeign.FeignAutoConfiguration
在这里插入图片描述

重要源码,feign 实现上下方隔离 的原理在以下代码中。

protected AnnotationConfigApplicationContext createContext(String name) {AnnotationConfigApplicationContext context;if (this.parent != null) {DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();......省略一些代码.......// 走这context = new AnnotationConfigApplicationContext(beanFactory);context.setClassLoader(this.parent.getClassLoader());}else {context = new AnnotationConfigApplicationContext();}if (this.configurations.containsKey(name)) {for (Class<?> configuration : this.configurations.get(name).getConfiguration()) {context.register(configuration);}}for (Map.Entry<String, C> entry : this.configurations.entrySet()) {if (entry.getKey().startsWith("default.")) {for (Class<?> configuration : entry.getValue().getConfiguration()) {context.register(configuration);}}}context.register(PropertyPlaceholderAutoConfiguration.class, this.defaultConfigType);context.getEnvironment().getPropertySources().addFirst(new MapPropertySource(this.propertySourceName,Collections.<String, Object>singletonMap(this.propertyName, name)));if (this.parent != null) {// Uses Environment from parent as well as beanscontext.setParent(this.parent);}context.setDisplayName(generateDisplayName(name));// 实例化此 spring 容器,servlet 类型 spring 容器作为父容器context.refresh();return context;
}

由上述代码可知,有 feign 的项目,启动时长会更长的,因为每个 provider feign 都会生成一个 spring 容器。spring 容器初始化是比较耗时的。

结束

Feign 使用及源码阅读至此结束,如有问题,欢迎评论区留言。

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

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

相关文章

课后作业7.3.1:构造一个自己的小操作系统

构造一个自己的 mini 操作系统 任务描述 请实现如下功能&#xff1a; 1.写一个命令解释器程序 mysh.c &#xff0c;其功能是接收用户输入的命令并给出反馈。要求该程序既支持内部命令 cd、sync、exit &#xff1b;也支持外部命令&#xff0c;即可以接收 cat、ls 等命令&#x…

数据结构与算法-Rust 版读书笔记-2线性数据结构-双端队列

数据结构与算法-Rust 版读书笔记-2线性数据结构-双端队列 1、双端队列 deque又称为双端队列&#xff0c;双端队列是与队列类似的项的有序集合。deque有两个端部&#xff1a;首端和尾端。deque不同于队列的地方就在于项的添加和删除是不受限制的&#xff0c;既可以从首尾两端添…

vue3封装接口

在src下面创建一个文件夹任意名称 我拿这个名字举例子了apiService 相当于创建一个新的文件 // 封装接口 // apiService.js import axios from axios;// 接口前缀 const API_BASE_URL 前缀;接口后缀export const registerUser async (fileData) > {try {const response …

数据分析 | 频率编码和标签编码 | Python代码

数据集见GitHub链接&#xff1a;https://github.com/ChuanTaoLai/Frequency-Encoding-And-Label-Encoding 标签编码&#xff1a; import pandas as pd from sklearn.preprocessing import LabelEncoderdata1 pd.read_excel(rD:\0文献整理\网络入侵检测\KDD99\KDDTrain.xlsx) …

透析跳跃游戏

关卡名 理解与贪心有关的高频问题 我会了✔️ 内容 1.理解跳跃游戏问题如何判断是否能到达终点 ✔️ 2.如果能到终点&#xff0c;如何确定最少跳跃次数 ✔️ 1. 跳跃游戏 leetCode 55 给定一个非负整数数组&#xff0c;你最初位于数组的第一个位置。数组中的每个元素代表…

微信商家收款码扣多少手续费

很多人想申请低手续费率的收款码不知从何下手&#xff0c;在参考了大量博客教学之后&#xff0c;终于搞懂了详细流程以及注意事项。在此记录一下。我申请的是一个只需要0.2%费率的微信收款码&#xff0c;申请时间是2022年2月12日。申请之前只需要准备营业执照和法人身份z&#…

JSON在线解析

JSON在线解析及格式化验证 - JSON.cn JSON在线视图查看器(Online JSON Viewer)

java中list的addAll用法详细实例?

List 的 addAll() 方法用于将一个集合中的所有元素添加到另一个 List 中。下面是一个详细的实例&#xff0c;展示了 addAll() 方法的使用&#xff1a; java Copy code import java.util.ArrayList; import java.util.List; public class AddAllExample { public static v…

设计模式: 关于编程范式的声明式和命令式编程及应用框架的开发和设计原则

编程范式 命令式编程声明式编程 上述两种范式是相对来说的 命令式编程 详细描述做事过程的方式就可以叫做 命令式例子: 张三妈妈让张三买食盐 拿钱&#xff0c;开门&#xff0c;下楼&#xff0c;到商店&#xff0c;付款&#xff0c;带着食盐回家 例子&#xff1a;在指定div…

验证二叉搜索树[中等]

优质博文&#xff1a;IT-BLOG-CN 一、题目 给你一个二叉树的根节点root&#xff0c;判断其是否是一个有效的二叉搜索树。有效 二叉搜索树定义如下&#xff1a; 【1】节点的左子树只包含 小于 当前节点的数。 【2】节点的右子树只包含 大于 当前节点的数。 【3】所有左子树和右…

Leetcode 40 组合总和 II

题意理解&#xff1a; 每个数字在每个组合中只能使用 一次 数字可以重复——>难点&#xff08;如何去重&#xff09; 每个组合和target 求组合&#xff0c;对合限制&#xff0c;考虑回溯的方法。——将其抽象为树结构。 树的宽度——分支大小 树的深度——最…

Spring IoC和DI

目录 一. Spring是什么 IoC DI 二. IoC&DI的使用 IoC 1.Controller&#xff08;控制器存储&#xff09; 2.Service&#xff08;服务存储&#xff09; 3.Repository&#xff08;仓库存储&#xff09; 4.Componemt&#xff08;组件存储&#xff09; 5.Configuratio…

解决Could not establish connection to : XHR failed

解决Could not establish connection to : XHR failed 问题描述 用vscode用远程连接服务器时总报上面的错误&#xff0c;用xshell和Xftp和vscode终端都可以连上&#xff0c;但是用vscode的ssh连接缺总报错&#xff0c;导致无法连接服务器进行代码调试 一、原因 原因可能是在…

【MATLAB】 数据、矩阵、行、列翻转

1.MATLAB函数fliplr 用法&#xff1a;fliplr(X) 功能&#xff1a;matlab中的fliplr函数实现矩阵的左右翻转。 fliplr(X)使矩阵X沿垂直轴左右翻转。 相关函数&#xff1a;flipud函数可以实现矩阵的上下翻转。 备注&#xff1a;matlab中提供了许多对矩阵操作的函数&#xff0c;可…

Go json 差异比较 json-diff(RFC6902)

Go json 差异比较 json-diff(RFC 6902) 毕业设计中过程中为了比较矢量图的差异而依据 RFC 6902 编写的一个包&#xff0c;现已开源&#xff1a; Json-diff 使用 go get -u github.com/520MianXiangDuiXiang520/json-diff序列化与反序列化 与官方 json 包的序列化和反序列化不…

后端开发面试题

这是一波今年7月份的大厂面试题&#xff0c;分享下&#xff5e;&#xff5e; Mybatis三级缓存 Mybatis懒加载 分布式事务 transaction gradle和maven区别 抽象类、多态 Springboot启动 ConcurrentHashMap 乐观锁、悲观锁 docker k8s常用命令 电商业务从什么维度分库分…

AcWing 95. 费解的开关(递推)

题目链接 活动 - AcWing 本活动组织刷《算法竞赛进阶指南》&#xff0c;系统学习各种编程算法。主要面向有一定编程基础的同学。https://www.acwing.com/problem/content/97/ 题解 只要第一行开关的状态确定&#xff0c;则所有开关的状态都可以被推出来。第一行开关总共有种操…

jemeter,同一线程组内,调用cookie实现接口关联

取cookie方式参考上一篇&#xff1a;jemeter&#xff0c;取“临时重定向的登录接口”响应头中的cookie-CSDN博客 元件结构 登录后要执行的接口为“api/get_event_list/”&#xff0c;在该HTTP请求下创建HTTP信息头管理器&#xff0c;配置如下&#xff1a; 执行测试后&#xff0…

【ensp实践】eNSP实战篇(4)用eNSP实验来认识什么是OSPF及OSPF配置?

OSPF目录 写在前面涉及知识一、什么是OSPF&#xff1f;二、OSPF特性&#xff08;优缺点&#xff09;2.1 OSPF优点2.2 OSPF缺点 三、OSPF实验3.1 打开ensp&#xff0c;添加设备3.2 建立连线3.3 配置及ospf命令【核心】3.3.1 配置PC机3.3.2 设置命令 3.4 验证效果3.4.1、验证OSPF…