Feign使用简介

基本用法

基本的使用如下所示,一个对于canonical Retrofit sample的适配。

  1. interface GitHub {
  2. // RequestLine注解声明请求方法和请求地址,可以允许有查询参数
  3. @RequestLine("GET /repos/{owner}/{repo}/contributors")
  4. List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
  5. }
  6.  
  7. static class Contributor {
  8. String login;
  9. int contributions;
  10. }
  11.  
  12. public static void main(String... args) {
  13. GitHub github = Feign.builder()
  14. .decoder(new GsonDecoder())
  15. .target(GitHub.class, "https://api.github.com");
  16.  
  17. // Fetch and print a list of the contributors to this library.
  18. List<Contributor> contributors = github.contributors("OpenFeign", "feign");
  19. for (Contributor contributor : contributors) {
  20. System.out.println(contributor.login + " (" + contributor.contributions + ")");
  21. }
  22. }

自定义

Feign 有许多可以自定义的方面。举个简单的例子,你可以使用 Feign.builder() 来构造一个拥有你自己组件的API接口。如下:

  1. interface Bank {
  2. @RequestLine("POST /account/{id}")
  3. Account getAccountInfo(@Param("id") String id);
  4. }
  5. ...
  6. // AccountDecoder() 是自己实现的一个Decoder
  7. Bank bank = Feign.builder().decoder(new AccountDecoder()).target(Bank.class, "https://api.examplebank.com");

多种接口

Feign可以提供多种API接口,这些接口都被定义为 Target<T> (默认的实现是 HardCodedTarget<T>), 它允许在执行请求前动态发现和装饰该请求。 
举个例子,下面的这个模式允许使用当前url和身份验证token来装饰每个发往身份验证中心服务的请求。

  1. CloudDNS cloudDNS = Feign.builder().target(new CloudIdentityTarget<CloudDNS>(user, apiKey));

示例

Feign 包含了 GitHub 和 Wikipedia 客户端的实现样例.相似的项目也同样在实践中运用了Feign。尤其是它的示例后台程序。


Feign集成模块

Feign 可以和其他的开源工具集成工作。你可以将这些开源工具集成到 Feign 中来。目前已经有的一些模块如下:

Gson

Gson 包含了一个编码器和一个解码器,这个可以被用于JSON格式的API。 
添加 GsonEncoder 以及 GsonDecoder 到你的 Feign.Builder 中, 如下:

  1. GsonCodec codec = new GsonCodec();
  2. GitHub github = Feign.builder()
  3. .encoder(new GsonEncoder())
  4. .decoder(new GsonDecoder())
  5. .target(GitHub.class, "https://api.github.com");

Maven依赖:

  1. <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
  2. <dependency>
  3. <groupId>com.netflix.feign</groupId>
  4. <artifactId>feign-gson</artifactId>
  5. <version>8.18.0</version>
  6. </dependency>

Jackson

Jackson 包含了一个编码器和一个解码器,这个可以被用于JSON格式的API。 
添加 JacksonEncoder 以及 JacksonDecoder 到你的 Feign.Builder 中, 如下:

  1. GitHub github = Feign.builder()
  2. .encoder(new JacksonEncoder())
  3. .decoder(new JacksonDecoder())
  4. .target(GitHub.class, "https://api.github.com");

Maven依赖:

  1. <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
  2. <dependency>
  3. <groupId>com.netflix.feign</groupId>
  4. <artifactId>feign-jackson</artifactId>
  5. <version>8.18.0</version>
  6. </dependency>

Sax

SaxDecoder 用于解析XML,并兼容普通JVM和Android。下面是一个配置sax来解析响应的例子:

  1. api = Feign.builder()
  2. .decoder(SAXDecoder.builder()
  3. .registerContentHandler(UserIdHandler.class)
  4. .build())
  5. .target(Api.class, "https://apihost");

Maven依赖:

  1. <dependency>
  2. <groupId>com.netflix.feign</groupId>
  3. <artifactId>feign-sax</artifactId>
  4. <version>8.18.0</version>
  5. </dependency>

JAXB

JAXB 包含了一个编码器和一个解码器,这个可以被用于XML格式的API。 
添加 JAXBEncoder 以及 JAXBDecoder 到你的 Feign.Builder 中, 如下:

  1. api = Feign.builder()
  2. .encoder(new JAXBEncoder())
  3. .decoder(new JAXBDecoder())
  4. .target(Api.class, "https://apihost");

Maven依赖:

  1. <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
  2. <dependency>
  3. <groupId>com.netflix.feign</groupId>
  4. <artifactId>feign-jaxb</artifactId>
  5. <version>8.18.0</version>
  6. </dependency>

JAX-RS

JAXRSContract 使用 JAX-RS 规范重写覆盖了默认的注解处理。下面是一个使用 JAX-RS 的例子:

  1. interface GitHub {
  2. @GET @Path("/repos/{owner}/{repo}/contributors")
  3. List<Contributor> contributors(@PathParam("owner") String owner, @PathParam("repo") String repo);
  4. }
  5. // contract 方法配置注解处理器,注解处理器定义了哪些注解和值是可以作用于接口的
  6. GitHub github = Feign.builder()
  7. .contract(new JAXRSContract())
  8. .target(GitHub.class, "https://api.github.com");

Maven依赖:

  1. <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
  2. <dependency>
  3. <groupId>com.netflix.feign</groupId>
  4. <artifactId>feign-jaxrs</artifactId>
  5. <version>8.18.0</version>
  6. </dependency>

OkHttp

OkHttpClient 使用 OkHttp 来发送 Feign 的请求,OkHttp 支持 SPDY (SPDY是Google开发的基于TCP的传输层协议,用以最小化网络延迟,提升网络速度,优化用户的网络使用体验),并有更好的控制http请求。 
要让 Feign 使用 OkHttp ,你需要将 OkHttp 加入到你的环境变量中区,然后配置 Feign 使用 OkHttpClient,如下:

  1. GitHub github = Feign.builder()
  2. .client(new OkHttpClient())
  3. .target(GitHub.class, "https://api.github.com");

Maven依赖:

  1. <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
  2. <dependency>
  3. <groupId>com.netflix.feign</groupId>
  4. <artifactId>feign-okhttp</artifactId>
  5. <version>8.18.0</version>
  6. </dependency>

Ribbon

RibbonClient 重写了 Feign 客户端的对URL的处理,其添加了 智能路由以及一些其他由Ribbon提供的弹性功能。 
集成Ribbon需要你将ribbon的客户端名称当做url的host部分来传递,如下:

  1. // myAppProd是你的ribbon client name
  2. MyService api = Feign.builder().client(RibbonClient.create()).target(MyService.class, "https://myAppProd");

Maven依赖:

  1. <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
  2. <dependency>
  3. <groupId>com.netflix.feign</groupId>
  4. <artifactId>feign-ribbon</artifactId>
  5. <version>8.18.0</version>
  6. </dependency>

Hystrix

HystrixFeign 配置了 Hystrix 提供的熔断机制。 
要在 Feign 中使用 Hystrix ,你需要添加Hystrix模块到你的环境变量,然后使用 HystrixFeign 来构造你的API:

  1. MyService api = HystrixFeign.builder().target(MyService.class, "https://myAppProd");

Maven依赖:

  1. <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
  2. <dependency>
  3. <groupId>com.netflix.feign</groupId>
  4. <artifactId>feign-hystrix</artifactId>
  5. <version>8.18.0</version>
  6. </dependency>

SLF4J

SLF4JModule 允许你使用 SLF4J 作为 Feign 的日志记录模块,这样你就可以轻松的使用 LogbackLog4J , 等 来记录你的日志. 
要在 Feign 中使用 SLF4J ,你需要添加SLF4J模块和对应的日志记录实现模块(比如Log4J)到你的环境变量,然后配置 Feign使用Slf4jLogger :

  1. GitHub github = Feign.builder()
  2. .logger(new Slf4jLogger())
  3. .target(GitHub.class, "https://api.github.com");

Maven依赖:

  1. <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
  2. <dependency>
  3. <groupId>com.netflix.feign</groupId>
  4. <artifactId>feign-slf4j</artifactId>
  5. <version>8.18.0</version>
  6. </dependency>

Feign 组成

Decoders

Feign.builder() 允许你自定义一些额外的配置,比如说如何解码一个响应。假如有接口方法返回的消息不是 ResponseStringbyte[] 或者 void 类型的,那么你需要配置一个非默认的解码器。 
下面是一个配置使用JSON解码器(使用的是feign-gson扩展)的例子:

  1. GitHub github = Feign.builder()
  2. .decoder(new GsonDecoder())
  3. .target(GitHub.class, "https://api.github.com");

假如你想在将响应传递给解码器处理前做一些额外的处理,那么你可以使用mapAndDecode方法。一个用例就是使用jsonp服务的时候:

  1. // 貌似1.8.0版本中沒有mapAndDecode这个方法。。。
  2. JsonpApi jsonpApi = Feign.builder()
  3. .mapAndDecode((response, type) -> jsopUnwrap(response, type), new GsonDecoder())
  4. .target(JsonpApi.class, "https://some-jsonp-api.com");

Encoders

发送一个Post请求最简单的方法就是传递一个 String 或者 byte[] 类型的参数了。你也许还需添加一个Content-Type请求头,如下:

  1. interface LoginClient {
  2. @RequestLine("POST /")
  3. @Headers("Content-Type: application/json")
  4. void login(String content);
  5. }
  6. ...
  7. client.login("{\"user_name\": \"denominator\", \"password\": \"secret\"}");

通过配置一个解码器,你可以发送一个安全类型的请求体,如下是一个使用 feign-gson 扩展的例子:

  1. static class Credentials {
  2. final String user_name;
  3. final String password;
  4.  
  5. Credentials(String user_name, String password) {
  6. this.user_name = user_name;
  7. this.password = password;
  8. }
  9. }
  10.  
  11. interface LoginClient {
  12. @RequestLine("POST /")
  13. void login(Credentials creds);
  14. }
  15. ...
  16. LoginClient client = Feign.builder()
  17. .encoder(new GsonEncoder())
  18. .target(LoginClient.class, "https://foo.com");
  19.  
  20. client.login(new Credentials("denominator", "secret"));

@Body templates

@Body注解申明一个请求体模板,模板中可以带有参数,与方法中 @Param 注解申明的参数相匹配,使用方法如下

  1. interface LoginClient {
  2.  
  3. @RequestLine("POST /")
  4. @Headers("Content-Type: application/xml")
  5. @Body("<login \"user_name\"=\"{user_name}\" \"password\"=\"{password}\"/>")
  6. void xml(@Param("user_name") String user, @Param("password") String password);
  7.  
  8. @RequestLine("POST /")
  9. @Headers("Content-Type: application/json")
  10. // json curly braces must be escaped!
  11. // 这里JSON格式需要的花括号居然需要转码,有点蛋疼了。
  12. @Body("%7B\"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D")
  13. void json(@Param("user_name") String user, @Param("password") String password);
  14. }
  15. ...
  16. // <login "user_name"="denominator" "password"="secret"/>
  17. client.xml("denominator", "secret");
  18. // {"user_name": "denominator", "password": "secret"}
  19. client.json("denominator", "secret");

Headers

Feign 支持给请求的api设置或者请求的客户端设置请求头

给API设置请求头

  • 使用 @Headers 设置静态请求头
  1. // 给BaseApi中的所有方法设置Accept请求头
  2. @Headers("Accept: application/json")
  3. interface BaseApi<V> {
  4. // 单独给put方法设置Content-Type请求头
  5. @Headers("Content-Type: application/json")
  6. @RequestLine("PUT /api/{key}")
  7. void put(@Param("key") String, V value);
  8. }
  • 设置动态值的请求头
  1. @RequestLine("POST /")
  2. @Headers("X-Ping: {token}")
  3. void post(@Param("token") String token);
  • 设置key和value都是动态的请求头 
    有些API需要根据调用时动态确定使用不同的请求头(e.g. custom metadata header fields such as “x-amz-meta-” or “x-goog-meta-“), 
    这时候可以使用 @HeaderMap 注解,如下:
  1. // @HeaderMap 注解设置的请求头优先于其他方式设置的
  2. @RequestLine("POST /")
  3. void post(@HeaderMap Map<String, Object> headerMap);

给Target设置请求头

有时我们需要在一个API实现中根据不同的endpoint来传入不同的Header,这个时候我们可以使用自定义的RequestInterceptor 或 Target来实现. 
通过自定义的 RequestInterceptor 来实现请查看 Request Interceptors 章节. 
下面是一个通过自定义Target来实现给每个Target设置安全校验信息Header的例子:

  1. static class DynamicAuthTokenTarget<T> implements Target<T> {
  2. public DynamicAuthTokenTarget(Class<T> clazz,
  3. UrlAndTokenProvider provider,
  4. ThreadLocal<String> requestIdProvider);
  5. ...
  6. @Override
  7. public Request apply(RequestTemplate input) {
  8. TokenIdAndPublicURL urlAndToken = provider.get();
  9. if (input.url().indexOf("http") != 0) {
  10. input.insert(0, urlAndToken.publicURL);
  11. }
  12. input.header("X-Auth-Token", urlAndToken.tokenId);
  13. input.header("X-Request-ID", requestIdProvider.get());
  14. return input.request();
  15. }
  16. }
  17. ...
  18. Bank bank = Feign.builder()
  19. .target(new DynamicAuthTokenTarget(Bank.class, provider, requestIdProvider));

这种方法的实现依赖于给Feign 客户端设置的自定义的RequestInterceptor 或 Target。可以被用来给一个客户端的所有api请求设置请求头。比如说可是被用来在header中设置身份校验信息。这些方法是在线程执行api请求的时候才会执行,所以是允许在运行时根据上下文来动态设置header的。 
比如说可以根据线程本地存储(thread-local storage)来为不同的线程设置不同的请求头。


高级用法

Base APIS

有些请求中的一些方法是通用的,但是可能会有不同的参数类型或者返回类型,这个时候可以这么用:

  1. // 通用API
  2. interface BaseAPI {
  3. @RequestLine("GET /health")
  4. String health();
  5. @RequestLine("GET /all")
  6. List<Entity> all();
  7. }
  8. // 继承通用API
  9. interface CustomAPI extends BaseAPI {
  10. @RequestLine("GET /custom")
  11. String custom();
  12. }
  13. // 各种类型有相同的表现形式,定义一个统一的API
  14. @Headers("Accept: application/json")
  15. interface BaseApi<V> {
  16. @RequestLine("GET /api/{key}")
  17. V get(@Param("key") String key);
  18. @RequestLine("GET /api")
  19. List<V> list();
  20. @Headers("Content-Type: application/json")
  21. @RequestLine("PUT /api/{key}")
  22. void put(@Param("key") String key, V value);
  23. }
  24. // 根据不同的类型来继承
  25. interface FooApi extends BaseApi<Foo> { }
  26. interface BarApi extends BaseApi<Bar> { }

Logging

你可以通过设置一个 Logger 来记录http消息,如下:

  1. GitHub github = Feign.builder()
  2. .decoder(new GsonDecoder())
  3. .logger(new Logger.JavaLogger().appendToFile("logs/http.log"))
  4. .logLevel(Logger.Level.FULL)
  5. .target(GitHub.class, "https://api.github.com");

也可以参考上面的 SLF4J 章节的说明

Request Interceptors

当你希望修改所有的的请求的时候,你可以使用Request Interceptors。比如说,你作为一个中介,你可能需要为每个请求设置 X-Forwarded-For

  1. static class ForwardedForInterceptor implements RequestInterceptor {
  2. @Override public void apply(RequestTemplate template) {
  3. template.header("X-Forwarded-For", "origin.host.com");
  4. }
  5. }
  6. ...
  7. Bank bank = Feign.builder()
  8. .decoder(accountDecoder)
  9. .requestInterceptor(new ForwardedForInterceptor())
  10. .target(Bank.class, "https://api.examplebank.com");

或者,你可能需要实现Basic Auth,这里有一个内置的基础校验拦截器 BasicAuthRequestInterceptor

  1. Bank bank = Feign.builder()
  2. .decoder(accountDecoder)
  3. .requestInterceptor(new BasicAuthRequestInterceptor(username, password))
  4. .target(Bank.class, "https://api.examplebank.com");

Custom @Param Expansion

在使用 @Param 注解给模板中的参数设值的时候,默认的是使用的对象的 toString() 方法的值,通过声明 自定义的Param.Expander,用户可以控制其行为,比如说格式化 Date 类型的值:

  1. // 通过设置 @Param 的 expander 为 DateToMillis.class 可以定义Date类型的值
  2. @RequestLine("GET /?since={date}")
  3. Result list(@Param(value = "date", expander = DateToMillis.class) Date date);

Dynamic Query Parameters

动态查询参数支持,通过使用 @QueryMap 可以允许动态传入请求参数,如下:

  1. @RequestLine("GET /find")
  2. V find(@QueryMap Map<String, Object> queryMap);

Static and Default Methods

如果你使用的是JDK 1.8+ 的话,那么你可以给接口设置统一的默认方法和静态方法,这个事JDK8的新特性,如下:

  1. interface GitHub {
  2. @RequestLine("GET /repos/{owner}/{repo}/contributors")
  3. List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
  4. @RequestLine("GET /users/{username}/repos?sort={sort}")
  5. List<Repo> repos(@Param("username") String owner, @Param("sort") String sort);
  6. default List<Repo> repos(String owner) {
  7. return repos(owner, "full_name");
  8. }
  9. /**
  10. * Lists all contributors for all repos owned by a user.
  11. */
  12. default List<Contributor> contributors(String user) {
  13. MergingContributorList contributors = new MergingContributorList();
  14. for(Repo repo : this.repos(owner)) {
  15. contributors.addAll(this.contributors(user, repo.getName()));
  16. }
  17. return contributors.mergeResult();
  18. }
  19. static GitHub connect() {
  20. return Feign.builder()
  21. .decoder(new GsonDecoder())
  22. .target(GitHub.class, "https://api.github.com");
  23. }
  24. }

Feign api调用方式的更多相关文章

  1. Azure Mobile Services的REST API调用方式和自定义API

    Azure Mobile Services(移动服务)是微软在Azure平台中提供的一种跨平台的移动应用后端服务,即移动后端即服务.支持.NET和JavaScript(Node.js)写后端代码:支持 ...

  2. SpringBoot之Feign调用方式比较

    一:事发原因 两个东家都使用SpringCloud,巴拉巴拉用上了Spring全家桶,从eureka到ribbon,从ribbon到feign,从feign到hystrix,然后在使用feign的时候 ...

  3. Saltstack的API接口与调用方式

     saltstack看起来是成为一个大规模自己主动化运维和云计算管理的一个框架,类似于SDK,并非像puppet仅仅成为一个工具.基于良好设计的API和清楚的思路,让salt的二次开发变得非常easy ...

  4. Feign服务调用请求方式及参数总结

    前言 最近做微服务架构的项目,在用feign来进行服务间的调用.在互调的过程中,难免出现问题,根据错误总结了一下,主要是请求方式的错误和接参数的错误造成的.在此进行一下总结记录.以下通过分为三种情况说 ...

  5. 小D课堂 - 新版本微服务springcloud+Docker教程_4-06 Feign核心源码解读和服务调用方式ribbon和Feign选择

    笔记 6.Feign核心源码解读和服务调用方式ribbon和Feign选择         简介: 讲解Feign核心源码解读和 服务间的调用方式ribbon.feign选择             ...

  6. 小D课堂 - 新版本微服务springcloud+Docker教程_4-05 微服务调用方式之feign 实战 订单调用商品服务

    笔记 5.微服务调用方式之feign 实战 订单调用商品服务     简介:改造电商项目 订单服务 调用商品服务获取商品信息         Feign: 伪RPC客户端(本质还是用http)    ...

  7. SpringCloud(5)---Feign服务调用

    SpringCloud(5)---Feign服务调用 上一篇写了通过Ribbon进行服务调用,这篇其它都一样,唯一不一样的就是通过Feign进行服务调用. 注册中心和商品微服务不变,和上篇博客一样,具 ...

  8. Spring Cloud Alibaba(8)---Feign服务调用

    Feign服务调用 有关Spring Cloud Alibaba之前写过五篇文章,这篇也是在上面项目的基础上进行开发. Spring Cloud Alibaba(1)---入门篇 Spring Clo ...

  9. Vue.js——使用$.ajax和vue-resource实现OAuth的注册、登录、注销和API调用

    概述 上一篇我们介绍了如何使用vue resource处理HTTP请求,结合服务端的REST API,就能够很容易地构建一个增删查改应用.这个应用始终遗留了一个问题,Web App在访问REST AP ...

随机推荐

  1. win10 ubuntu 同一硬盘双系统安装和启动设置

    1.了解启动的顺序 电脑开机--->  BIOS 设置 ----> 硬盘(MBR)/ GPT格式里的ESP分区 --->  (UEFI/GRUB)目录里的 *****.efi  -- ...

  2. 2017.4.4 TCP/IP三次握手,四次挥手

    之前在电话面试的时候,被问到,所以找到一个超级容易理解的图片,自己保存,也算分享.

  3. (19)jQuery操作文本和属性

    <!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>jq ...

  4. C++学习(二十四)(C语言部分)之 结构体1

    1.结构体 存放多个不同类型的数据 但是是相关联的 数组 存放多个相同类型的数据 结构体是存放多个相关联的不同类型的数组 struct 定义一个结构体类型 自定义类型 2.结构体定义方式 定义类型最通 ...

  5. PS学习之合成特效:被风沙侵蚀的动物们

    素材 大象 尘埃 裂纹 沙子 土地 正式操作: 打开PS 新建一个文件 选国际标准纸张  给分辨率为72(分辨率越大越占内存) 然后确定  将图片旋转90度(图像——旋转——(顺/逆)90度) 下面选 ...

  6. 【BZOJ3244】【UOJ#122】【NOI2013]树的计数

    NOI都是酱的题怎么玩啊,哇.jpg 原题: 我们知道一棵有根树可以进行深度优先遍历(DFS)以及广度优先遍历(BFS)来生成这棵树的DFS序以及BFS序.两棵不同的树的DFS序有可能相同,并且它们的 ...

  7. python实现单链表的翻转

    #!/usr/bin/env python #coding = utf-8 class Node:     def __init__(self,data=None,next = None):      ...

  8. linux面试题(自己添加了一些注释说明)

    1.linux如何挂在windows下的共享目录 首先需要在Windows中创建一个文件夹用来共享,例如下面就是server是用来共享的,貌似在哪个位置创建都可以,我是在d盘创建的 1 mount.c ...

  9. for in和for of

  10. linux centos6 yum 安装lamp

    centos 6.5 1.yum安装和源代码编译在使用的时候没啥区别,但是安装的过程就大相径庭了,yum只需要3个命令就可以完成,源代码需要13个包,还得加压编译,步骤很麻烦,而且当做有时候会出错,源 ...