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.pswp.cn/news/214536.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/214536.shtml
英文地址,請注明出處:http://en.pswp.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…