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. Redis分布式锁这样用,有坑?

    背景 在微服务项目中,大家都会去使用到分布式锁,一般也是使用Redis去实现,使用RedisTemplate.Redisson.RedisLockRegistry都行,公司的项目中,使用的是Redis ...

  2. Kubernetes入门实践(环境搭建)

    容器技术只是解决了运维部署工作中的一个很小的问题,在现实生产环境中,除了最基本的安装,还会各式各样的需求,比如服务发现.负载均衡.状态监控.健康检查.扩容缩容.应用迁移.高可用等等.这些容器之上的管理 ...

  3. Callback详解

    Callbacks Callback Registration 在 Rails 中,回调(Callbacks)是一种在模型对象的生命周期中执行特定代码的机制.回调可以在模型对象的创建.更新.删除等操作 ...

  4. Sentinel为什么这么强,我扒了扒背后的实现原理

    大家好,我是三友~~ 最近我在整理代码仓库的时候突然发现了被尘封了接近两年之久的Sentinel源码库 两年前我出于好奇心扒了一下Sentinel的源码,但是由于Sentinel本身源码并不复杂,在简 ...

  5. Python-BeautifulReport的简单使用

    一.简介 BeautifulReport.report report ( filename -> 测试报告名称, 如果不指定默认文件名为report.html description -> ...

  6. 基于pyinstaller的python打包工具

    以下是软件链接:https://mysecreat.lanzoub.com/iZPGf0swgtbc 软件功能:可以对py文件进行打包,功能基于pyinstaller模块,因此需要安装python环境 ...

  7. Kubernetes Gateway API 深入解读和落地指南

    背景 Kubernetes Gateway API 是 Kubernetes 1.18 版本引入的一种新的 API 规范,是 Kubernetes 官方正在开发的新的 API,Ingress 是 Ku ...

  8. 【Redis】-使用Lua脚本解决多线程下的超卖问题以及为什么?

    一.多线程下引起的超卖问题呈现1.1.我先初始化库存数量为1.订单数量为0 1.2.开启3个线程去执行业务 业务为:判断如果说库存数量大于0,则库存减1,订单数量加1 结果为:库存为-2,订单数量为3 ...

  9. vscode取消“禁用错误波形曲线”

    刚刚不小心点到了vscode的禁用错误波形曲线,导致现在没有报错提醒了,上网查了一下,重新打开错误曲线的方法是 1.按住Cctrl+shift+p 2.搜索 启用错误波形曲线,选择打开,就可以了

  10. MySQL中的Join 的算法(NLJ、BNL、BKA)

    本文已收录至Github,推荐阅读 Java随想录 微信公众号:Java随想录 目录 摘要 什么是Join Index Nested-Loop Join Block Nested-Loop Join ...