Spring Cloud 之OpenFeign

一:简介

​ Feign是一个声明式(对比RestTemplate编程式)的服务客户端,即通过@FeignClient注解即可声明一个接口(interface)。还支持多种插拔式的配置如encoders/decoders(加解码),clients(不同的链接框架)...... 。Spring Cloud 集成了 Eureka、Spring Cloud Breaker 以及 Spring Cloud LoadBalancer,便可实现 Feign 负载平衡的 http 客户端。

二: 使用方式一(单独使用)

2.1:引入依赖
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>??feign.version??</version>
</dependency>
2.2:定义接口
interface GitHub {
@RequestLine("GET /repos/{owner}/{repo}/contributors")
List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
} public static class Contributor {
String login;
int contributions;
}
2.3 : 构造Feign的 http 客户端 示例
public class MyApp {
public static void main(String... args) {
GitHub github = Feign.builder()
.decoder(new GsonDecoder())
.target(GitHub.class, "https://api.github.com"); List<Contributor> contributors = github.contributors("OpenFeign", "feign");
for (Contributor contributor : contributors) {
System.out.println(contributor.login + " (" + contributor.contributions + ")");
}
}
}

示例解释:

2.3.1 :接口地址‘ https://api.github.com/repos/OpenFeign/feign/contributors’是一个获取github上OpenFeign项目的贡献者名单信息。
2.3.2 :Feign.builder(构建者模式(23种设计模式之一)).decoder指定解析器(返回的是json数组).target指定指定目标对象(接口和url)
2.3.3 :自定义其他参数

.encoder(加析器),errorDecoder(异常解析器).client(指定使用的客户端)....再次不一一介绍。

小结: 通过简介以及一个简单的示例,我们已经明了了Feign用法和架构,下面就看springcloud如何集成Feign

三:springcloud集成Feign

3.1:启动类加@EnableFeignClients注解开启声明式Feign,
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3.2: 通过interface定义接口地址(复用2.2:定义接口)
interface GitHub {
@RequestLine("GET /repos/{owner}/{repo}/contributors")
List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
}
3.3:通过@FeignClient注解(相当于 Feign.builder()) 定义远程服务地址和其他组件
   @FeignClient(url = "服务名地址(https://api.github.com)" ,value = "服务名(springboot项目的项目名与url二选一)")
interface GitHub {
@RequestLine("GET /repos/{owner}/{repo}/contributors")
List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
}

四:集成feign后的常见需求

4.1 Feign调用失败后的错误分析

fallbackFactory :错误后的返回信息 推荐使用相比fallback可辨知错误原因)

fallback:错误后的返回信息

#配置文件中需开启错误分析
feign:
hystrix: # 老版本
enabled: true
circuitbreaker: #新版本
enabled: true
4.1.2 fallbackFactory 示例
@Component
public class FallbackFactoryGitHub implements FallbackFactory<GitHub> {
private static final Logger logger = LoggerFactory.getLogger(GitHub.class); @Override
public GitHub create(Throwable throwable) {
return new GitHub() {
@Override
public String contributors( String owner, String repo) {
logger.error("contributors", throwable);
return throwable.getMessage();
}
.....
};
}
}

4.2 服务间通过Feign调用,会丢失请求头的信息

4.2.1 步骤一:定义RequestInterceptor传的请求头信息:
@Bean
public RequestInterceptor headerInterceptor() {
return template -> {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (null != attributes) {
attributes.getRequest();
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
// 跳过 content-length
if (name.equals("content-length")){
continue;
}
template.header(name, values);
}
}
}
};
}
4.2.2 指定配置
@FeignClient(.... , configuration = XXX.class)

五:参考资料

5.1 https://docs.spring.io/spring-cloud-openfeign/docs/3.1.8/reference/html

5.2 https://github.com/OpenFeign/feign

最后期待负载均衡客户段是如何实现的

Spring Cloud 之OpenFeign的更多相关文章

  1. Spring cloud简单学习总结

    微服务简介 一.spring boot和spring cloud 的关系 spring boot来写各个拆分出来的微服务,spring  cloud把各个微服务联系起来,比如各个微服务通过eurke找 ...

  2. [Spring Cloud实战 | 第六篇:Spring Cloud Gateway+Spring Security OAuth2+JWT实现微服务统一认证授权

    一. 前言 本篇实战案例基于 youlai-mall 项目.项目使用的是当前主流和最新版本的技术和解决方案,自己不会太多华丽的言辞去描述,只希望能勾起大家对编程的一点喜欢.所以有兴趣的朋友可以进入 g ...

  3. Spring Cloud实战 | 最终篇:Spring Cloud Gateway+Spring Security OAuth2集成统一认证授权平台下实现注销使JWT失效方案

    一. 前言 在上一篇文章介绍 youlai-mall 项目中,通过整合Spring Cloud Gateway.Spring Security OAuth2.JWT等技术实现了微服务下统一认证授权平台 ...

  4. 1.入门篇十分钟了解Spring Cloud

    文章目录 Spring Cloud入门系列汇总 为什么需要学习Spring Cloud 什么是Spring Cloud 设计目标与优缺点 设计目标 优缺点 Spring Cloud发展前景 整体架构 ...

  5. vue+uni-app商城实战 | 第一篇:【有来小店】微信小程序快速开发接入Spring Cloud OAuth2认证中心完成授权登录

    一. 前言 本篇通过实战来讲述如何使用uni-app快速进行商城微信小程序的开发以及小程序如何接入后台Spring Cloud微服务. 有来商城 youlai-mall 项目是一套全栈商城系统,技术栈 ...

  6. 【Spring Cloud + Vue 有来商城】研发小组开发规范全方位梳理

    项目演示 后端 Spring Cloud实战 | 第一篇:Windows搭建Nacos服务 Spring Cloud实战 | 第二篇:Spring Cloud整合Nacos实现注册中心 Spring ...

  7. Spring Cloud实战 | 最八篇:Spring Cloud +Spring Security OAuth2+ Axios前后端分离模式下无感刷新实现JWT续期

    一. 前言 记得上一篇Spring Cloud的文章关于如何使JWT失效进行了理论结合代码实践的说明,想当然的以为那篇会是基于Spring Cloud统一认证架构系列的最终篇.但关于JWT另外还有一个 ...

  8. Spring Cloud实战 | 第九篇:Spring Cloud整合Spring Security OAuth2认证服务器统一认证自定义异常处理

    本文完整代码下载点击 一. 前言 相信了解过我或者看过我之前的系列文章应该多少知道点我写这些文章包括创建 有来商城youlai-mall 这个项目的目的,想给那些真的想提升自己或者迷茫的人(包括自己- ...

  9. Spring Cloud实战 | 第十篇 :Spring Cloud + Seata 1.4.1 + Nacos1.4.0 整合实现微服务架构中逃不掉的话题分布式事务

    Seata分布式事务在线体验地址:https://www.youlai.store 本篇完整源码地址:https://github.com/hxrui/youlai-mall 有想加入开源项目开发的童 ...

  10. Spring Cloud实战: 基于Spring Cloud Gateway + vue-element-admin 实现的RBAC权限管理系统,实现网关对RESTful接口方法权限和自定义Vue指令对按钮权限的细粒度控制

    一. 前言 信我的哈,明天过年. 这应该是农历年前的关于开源项目 的最后一篇文章了. 有来商城 是基于 Spring Cloud OAuth2 + Spring Cloud Gateway + JWT ...

随机推荐

  1. Function-advanced

    函数进阶 1. 函数防抖 在频率触发的情况下 只有等待一定的时间才会触发 执行一次代码 特点 执行之前先清除之前的即将执行操作 保证只有最后一次生效 优化高频执行JS代码操作 提高性能 防抖代码实现 ...

  2. 【解决方法】windows连接域时报错:An Active Directory Domain Controller(AD DC) for the domain“chinaskills.com“....

    目录-快速跳转 问题描述 原因分析: 解决方案: 附言: 问题描述 操作环境与场景: 在 VM 内 windos 2019 在连接到域时,提示报错: An Active Directory Domai ...

  3. 2020-09-19:TCP状态有哪些?

    福哥答案2020-09-19:#福大大架构师每日一题# [答案来自此链接](https://www.zhihu.com/question/421833613) 11种状态1.CLOSED状态:初始状态 ...

  4. 2022-07-19:f(i) : i的所有因子,每个因子都平方之后,累加起来。 比如f(10) = 1平方 + 2平方 + 5平方 + 10平方 = 1 + 4 + 25 + 100 = 130。

    2022-07-19:f(i) : i的所有因子,每个因子都平方之后,累加起来. 比如f(10) = 1平方 + 2平方 + 5平方 + 10平方 = 1 + 4 + 25 + 100 = 130. ...

  5. 2020-12-29:mysql中,innodb表里,某一条数据删除了之后,这条数据会被真实的擦掉吗,还是删除了关系?

    福哥答案2020-12-29:[答案来自此链接,答案相当详细:](https://www.zhihu.com/question/436957843)面试的时候受 <MySQL技术内幕 InnoD ...

  6. 2021-08-21:给定一个数组arr,长度为N > 1,从中间切一刀,保证左部分和右部分都有数字,一共有N-1种切法,如此多的切法中,每一种都有:绝对值(左部分最大值 – 右部分最大值)。返回最大

    2021-08-21:给定一个数组arr,长度为N > 1,从中间切一刀,保证左部分和右部分都有数字,一共有N-1种切法,如此多的切法中,每一种都有:绝对值(左部分最大值 – 右部分最大值).返 ...

  7. Requested setting LOGGING_CONFIG, but settings are not configured

  8. 什么是DOM和BOM?

    DOM:文档对象模型,描述了处理网页内容的方法和接口.最根本对象是document 由于DOM的操作对象是文档,所以DOM和浏览器没有直接关系 BOM:浏览器对象模型,描述了与浏览器进行交互的方法和接 ...

  9. AcWing 1019. 庆功会

    为了庆贺班级在校运动会上取得全校第一名成绩,班主任决定开一场庆功会,为此拨款购买奖品犒劳运动员. 期望拨款金额能购买最大价值的奖品,可以补充他们的精力和体力. 输入格式 第一行二个数n,m,其中n代表 ...

  10. 代码随想录算法训练营Day11 栈与队列|20. 有效的括号  1047. 删除字符串中的所有相邻重复项  150. 逆波兰表达式求值

    20.有效的括号 题目链接:20.有效的括号 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭合 ...