OpenFeign是什么

随着业务的增多,我们的单体应用越来越复杂,单机已经难以满足性能的需求,这时候出现了分布式。分布式通讯除了RPC, REST HTTP请求是最简单的一种方式。OpenFeign是Netflix开源的参照Retrofit, JAXRS-2.0, and WebSocket的一个http client客户端,致力于减少http client客户端构建的复杂性。

官方用法

github提供了一个简单的demo,很容易理解。

interface GitHub {
@RequestLine("GET /repos/{owner}/{repo}/contributors")
List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
} static class Contributor {
String login;
int contributions;
} public static void main(String... args) {
GitHub github = Feign.builder()
.decoder(new GsonDecoder())
.target(GitHub.class, "https://api.github.com"); // Fetch and print a list of the contributors to this library.
List<Contributor> contributors = github.contributors("OpenFeign", "feign");
for (Contributor contributor : contributors) {
System.out.println(contributor.login + " (" + contributor.contributions + ")");
}
}

简单的说,这么用没问题。但如果想要集成到系统中,关于Hystrix的配置还需要自己指定。为此,我单独把配置方案提炼了一下。

项目地址: https://github.com/Ryan-Miao/springboot-starter-feign

本项目提供了一个开箱即用的spring boot feign starter, 基于默认的约定配置

来简化和优化OpenFeign的使用流程.

How to use

引入repo

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

引入依赖

<dependency>
<groupId>com.github.Ryan-Miao</groupId>
<artifactId>springboot-starter-feign</artifactId>
<version>1.1</version>
</dependency>

在springboot 项目中添加Configuration

@Autowired
private Environment environment; @Bean
public FeignFactory feignFactory() {
return new FeignFactory(environment, hystrixConfigurationProperties());
} @Bean
public HystrixConfigurationProperties hystrixConfigurationProperties() {
return new HystrixConfigurationProperties();
}

然后就可以使用了。

使用和配置

约定了一些配置,大概如下

feign:
hystrixConfig:
"hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds": 8000
"hystrix.command.GithubConnector#getRepos.execution.isolation.thread.timeoutInMilliseconds": 15000
endpointConfig:
GithubConnector:
default:
url: https://api.github.com
readTimeoutMillis: 8000
connectTimeoutMillis: 5000
getRepos:
url: https://api.github.com
readTimeoutMillis: 15000
connectTimeoutMillis: 10000
  • feign是配置的第一个索引
  • hystrixConfig是hystrix的配置,更多配置见Hystrix
  • endpointConfig是我们远程请求的host和超时配置,其中,第一个节点为Connector class

    的名称,下一个是具体到某个请求的key,整个Connector class的默认配置是default

    节点,如果该Connector里的某个请求的超时比较长,需要单独设置,则会覆盖默认节点。

    另外,hystrix的超时配置commankey为[connectorClassName][#][methodName]

定义一个GithubConnector,继承com.miao.connect.Connector

public interface GithubConnector extends Connector {

    @RequestLine("GET /users/{username}")
@Headers({"Content-Type: application/json"})
GithubUser getGithubUser(@Param("username") String username); @RequestLine("GET /users/{username}/repos")
@Headers({"Content-Type: application/json"})
Observable<String> getRepos(@Param("username") String username);
}

调用

@Autowired
private FeignFactory feignFactory; @GetMapping("/profile/{username}")
public GithubUser getProfile(@PathVariable String username) {
//采用Jackson作为编码和解码类库,url和超时配置按照default,即读取feign.endpointConfig.GithubConnector.default
final GithubConnector connector = feignFactory.builder().getConnector(GithubConnector.class);
return connector.getGithubUser(username);
} @GetMapping("/repos/{username}")
public String getUserRepos(@PathVariable String username) {
//用String来接收返回值, url和超时单独指定配置,因为请求时间较长
//采用connector的method来当做获取配置的key,即读取feign.endpointConfig.GithubConnector.getRepos
final GithubConnector connector = feignFactory.builder()
.connectorMethod("getRepos")
.stringDecoder() //默认使用jackson作为序列化工具,这里接收string,使用StringDecoder
.getConnector(GithubConnector.class);
return connector.getRepos(username)
.onErrorReturn(e -> {
LOGGER.error("请求出错", e);
Throwable cause = e.getCause();
if (cause instanceof FeignErrorException) {
throw (FeignErrorException) cause;
}
throw new RuntimeException("请求失败", e);
}).toBlocking().first();
}

具体见使用示例example

相比原生有什么区别?

最大的区别是hystrix配置的内容,原生并没有提供hystrix相关配置,需要自己额外

准备。这里集成hystrix的约定,只要按照hystrix官方参数配置即可。

然后是缓存,在使用原生OpenFeign的过程中发现每次请求都要创建一个Connector,

而且Connector的创建又依赖一大堆别的class。对于我们远程调用比较频繁的应用来说,

增大了垃圾收集器的开销,我们其实不想回收。所以对Connector做了缓存。

其他用法同OpenFeign。

OpenFeign封装为springboot starter的更多相关文章

  1. 从头带你撸一个Springboot Starter

    我们知道 SpringBoot 提供了很多的 Starter 用于引用各种封装好的功能: 名称 功能 spring-boot-starter-web 支持 Web 开发,包括 Tomcat 和 spr ...

  2. 小D课堂 - 零基础入门SpringBoot2.X到实战_第7节 SpringBoot常用Starter介绍和整合模板引擎Freemaker、thymeleaf_28..SpringBoot Starter讲解

    笔记 1.SpringBoot Starter讲解     简介:介绍什么是SpringBoot Starter和主要作用 1.官网地址:https://docs.spring.io/spring-b ...

  3. SpringBoot Starter机制 - 自定义Starter

    目录 前言 1.起源 2.SpringBoot Starter 原理 3.自定义 Starter 3.1 创建 Starter 3.2 测试自定义 Starter 前言         最近在学习Sp ...

  4. 自定义springboot - starter 实现日志打印,并支持动态可插拔

    1. starter 命名规则: springboot项目有很多专一功能的starter组件,命名都是spring-boot-starter-xx,如spring-boot-starter-loggi ...

  5. SpringBoot starter 作用在什么地方?

    依赖管理是所有项目中至关重要的一部分.当一个项目变得相当复杂,管理依赖会成为一个噩梦,因为当中涉及太多 artifacts 了. 这时候 SpringBoot starter 就派上用处了.每一个 s ...

  6. SpringBoot Starter缘起

    SpringBoot通过SpringBoot Starter零配置自动加载第三方模块,只需要引入模块的jar包不需要任何配置就可以启用模块,遵循约定大于配置的思想. 那么如何编写一个SpringBoo ...

  7. 如何使用SpringBoot封装自己的Starter

    作者:Sans_ juejin.im/post/5cb880c2f265da03981fc031 一.说明 我们在使用SpringBoot的时候常常要引入一些Starter,例如spring-boot ...

  8. SpringBoot封装自己的Starter

    https://juejin.im/post/5cb880c2f265da03981fc031 一.说明 我们在使用SpringBoot的时候常常要引入一些Starter,例如spring-boot- ...

  9. SpringBoot - Starter

    If you work in a company that develops shared libraries, or if you work on an open-source or commerc ...

随机推荐

  1. Delphi 资源管理器套件

    需要个类似资源管理器的东西, 首先试了下 TDriveComboBox.TDirectoryListBox.TFileListBox, 嘿! Win31 时代的东西, 不是一般地丑. 试了下 Vcl. ...

  2. MikroTik RouterOS使用VirtualBox挂载物理硬盘作为虚拟机硬盘进行安装

    说明:这一切似乎在Windows下更好操作.虚拟机操作不是难点,难点在于虚拟磁盘的转换挂载 一.先挂载硬盘 # 创建虚拟镜像并映射到物理硬盘 cd "c:\Program Files\Ora ...

  3. 从PHP客户端看MongoDB通信协议(转)

    MongoDB 的 PHP 客户端有一个 MongoCursor 类,它是用于获取一次查询结果集的句柄(或者叫游标),这个简单的取数据操作,内部实现其实不是那么简单.本文就通过对 MongoCurso ...

  4. STM32 通用定时器相关寄存器

    TIMx_CR1(控制寄存器1) 9-8位:CKD[1:0]时钟分频因子,定义在定时器时钟(CK_INT)频率与数字滤波器(ETR,TIx)使用的采样频率之间的分频比例. 定义:00(tDTS = t ...

  5. Implementation of Serial Wire JTAG flash programming in ARM Cortex M3 Processors

    Implementation of Serial Wire JTAG flash programming in ARM Cortex M3 Processors The goal of the pro ...

  6. 【Unity 3D】碰撞检测

    在unity3d中,能检测碰撞发生的方式有两种, 碰撞器 触发器 概念:     (一)碰撞器是一群组件,它包含了很多种类,比如:Box Collider,Capsule Collider等,这些碰撞 ...

  7. javascript 编辑网页

    javascript:document.body.contentEditable='true';document.designMode='on'; void 0 出处:http://zhidao.ba ...

  8. [Winform]检测exe是否已经运行,并将其置顶

    摘要 在很多pc应用中,基本上都需要有这样的判断,保证在一个终端只运行一个winform的client.并且如果最小化了,用户再次双击桌面图标的时候,将client置顶显示. 解决方案 需要使用win ...

  9. 交叉编译gdb和gdbserver

    从http://ftp.gnu.org/gnu/gdb/下载最新的gdb,我下载的是gdb-8.0. 编译aarch32(>armv5): #!/bin/bash export CC=arm-n ...

  10. C#各种泛型集合体验

    本篇体验除Queue<T>和Stack<T>之外的其它泛型集合. SortedList<TKey, TValue> SortedList<TKey, TVal ...