Feign api调用方式
Feign使用简介
基本用法
基本的使用如下所示,一个对于canonical Retrofit sample的适配。
- interface GitHub {
- // RequestLine注解声明请求方法和请求地址,可以允许有查询参数
- @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 + ")");
- }
- }
自定义
Feign
有许多可以自定义的方面。举个简单的例子,你可以使用 Feign.builder()
来构造一个拥有你自己组件的API接口。如下:
- interface Bank {
- @RequestLine("POST /account/{id}")
- Account getAccountInfo(@Param("id") String id);
- }
- ...
- // AccountDecoder() 是自己实现的一个Decoder
- Bank bank = Feign.builder().decoder(new AccountDecoder()).target(Bank.class, "https://api.examplebank.com");
多种接口
Feign
可以提供多种API接口,这些接口都被定义为 Target<T>
(默认的实现是 HardCodedTarget<T>
), 它允许在执行请求前动态发现和装饰该请求。
举个例子,下面的这个模式允许使用当前url和身份验证token来装饰每个发往身份验证中心服务的请求。
- 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
中, 如下:
- GsonCodec codec = new GsonCodec();
- GitHub github = Feign.builder()
- .encoder(new GsonEncoder())
- .decoder(new GsonDecoder())
- .target(GitHub.class, "https://api.github.com");
Maven依赖:
- <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
- <dependency>
- <groupId>com.netflix.feign</groupId>
- <artifactId>feign-gson</artifactId>
- <version>8.18.0</version>
- </dependency>
Jackson
Jackson 包含了一个编码器和一个解码器,这个可以被用于JSON格式的API。
添加 JacksonEncoder
以及 JacksonDecoder
到你的 Feign.Builder
中, 如下:
- GitHub github = Feign.builder()
- .encoder(new JacksonEncoder())
- .decoder(new JacksonDecoder())
- .target(GitHub.class, "https://api.github.com");
Maven依赖:
- <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
- <dependency>
- <groupId>com.netflix.feign</groupId>
- <artifactId>feign-jackson</artifactId>
- <version>8.18.0</version>
- </dependency>
Sax
SaxDecoder
用于解析XML,并兼容普通JVM和Android。下面是一个配置sax来解析响应的例子:
- api = Feign.builder()
- .decoder(SAXDecoder.builder()
- .registerContentHandler(UserIdHandler.class)
- .build())
- .target(Api.class, "https://apihost");
Maven依赖:
- <dependency>
- <groupId>com.netflix.feign</groupId>
- <artifactId>feign-sax</artifactId>
- <version>8.18.0</version>
- </dependency>
JAXB
JAXB 包含了一个编码器和一个解码器,这个可以被用于XML格式的API。
添加 JAXBEncoder
以及 JAXBDecoder
到你的 Feign.Builder
中, 如下:
- api = Feign.builder()
- .encoder(new JAXBEncoder())
- .decoder(new JAXBDecoder())
- .target(Api.class, "https://apihost");
Maven依赖:
- <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
- <dependency>
- <groupId>com.netflix.feign</groupId>
- <artifactId>feign-jaxb</artifactId>
- <version>8.18.0</version>
- </dependency>
JAX-RS
JAXRSContract
使用 JAX-RS 规范重写覆盖了默认的注解处理。下面是一个使用 JAX-RS 的例子:
- interface GitHub {
- @GET @Path("/repos/{owner}/{repo}/contributors")
- List<Contributor> contributors(@PathParam("owner") String owner, @PathParam("repo") String repo);
- }
- // contract 方法配置注解处理器,注解处理器定义了哪些注解和值是可以作用于接口的
- GitHub github = Feign.builder()
- .contract(new JAXRSContract())
- .target(GitHub.class, "https://api.github.com");
Maven依赖:
- <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
- <dependency>
- <groupId>com.netflix.feign</groupId>
- <artifactId>feign-jaxrs</artifactId>
- <version>8.18.0</version>
- </dependency>
OkHttp
OkHttpClient 使用 OkHttp
来发送 Feign
的请求,OkHttp
支持 SPDY
(SPDY是Google开发的基于TCP的传输层协议,用以最小化网络延迟,提升网络速度,优化用户的网络使用体验),并有更好的控制http请求。
要让 Feign
使用 OkHttp
,你需要将 OkHttp
加入到你的环境变量中区,然后配置 Feign
使用 OkHttpClient
,如下:
- GitHub github = Feign.builder()
- .client(new OkHttpClient())
- .target(GitHub.class, "https://api.github.com");
Maven依赖:
- <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
- <dependency>
- <groupId>com.netflix.feign</groupId>
- <artifactId>feign-okhttp</artifactId>
- <version>8.18.0</version>
- </dependency>
Ribbon
RibbonClient
重写了 Feign
客户端的对URL的处理,其添加了 智能路由以及一些其他由Ribbon提供的弹性功能。
集成Ribbon需要你将ribbon的客户端名称当做url的host部分来传递,如下:
- // myAppProd是你的ribbon client name
- MyService api = Feign.builder().client(RibbonClient.create()).target(MyService.class, "https://myAppProd");
Maven依赖:
- <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
- <dependency>
- <groupId>com.netflix.feign</groupId>
- <artifactId>feign-ribbon</artifactId>
- <version>8.18.0</version>
- </dependency>
Hystrix
HystrixFeign
配置了 Hystrix
提供的熔断机制。
要在 Feign
中使用 Hystrix
,你需要添加Hystrix
模块到你的环境变量,然后使用 HystrixFeign
来构造你的API:
- MyService api = HystrixFeign.builder().target(MyService.class, "https://myAppProd");
Maven依赖:
- <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
- <dependency>
- <groupId>com.netflix.feign</groupId>
- <artifactId>feign-hystrix</artifactId>
- <version>8.18.0</version>
- </dependency>
SLF4J
SLF4JModule 允许你使用 SLF4J
作为 Feign
的日志记录模块,这样你就可以轻松的使用 Logback
, Log4J
, 等 来记录你的日志.
要在 Feign
中使用 SLF4J
,你需要添加SLF4J
模块和对应的日志记录实现模块(比如Log4J)到你的环境变量,然后配置 Feign
使用Slf4jLogger
:
- GitHub github = Feign.builder()
- .logger(new Slf4jLogger())
- .target(GitHub.class, "https://api.github.com");
Maven依赖:
- <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-gson -->
- <dependency>
- <groupId>com.netflix.feign</groupId>
- <artifactId>feign-slf4j</artifactId>
- <version>8.18.0</version>
- </dependency>
Feign 组成
Decoders
Feign.builder()
允许你自定义一些额外的配置,比如说如何解码一个响应。假如有接口方法返回的消息不是 Response
, String
, byte[]
或者 void
类型的,那么你需要配置一个非默认的解码器。
下面是一个配置使用JSON解码器(使用的是feign-gson扩展)的例子:
- GitHub github = Feign.builder()
- .decoder(new GsonDecoder())
- .target(GitHub.class, "https://api.github.com");
假如你想在将响应传递给解码器处理前做一些额外的处理,那么你可以使用mapAndDecode
方法。一个用例就是使用jsonp服务的时候:
- // 貌似1.8.0版本中沒有mapAndDecode这个方法。。。
- JsonpApi jsonpApi = Feign.builder()
- .mapAndDecode((response, type) -> jsopUnwrap(response, type), new GsonDecoder())
- .target(JsonpApi.class, "https://some-jsonp-api.com");
Encoders
发送一个Post请求最简单的方法就是传递一个 String
或者 byte[]
类型的参数了。你也许还需添加一个Content-Type请求头,如下:
- interface LoginClient {
- @RequestLine("POST /")
- @Headers("Content-Type: application/json")
- void login(String content);
- }
- ...
- client.login("{\"user_name\": \"denominator\", \"password\": \"secret\"}");
通过配置一个解码器,你可以发送一个安全类型的请求体,如下是一个使用 feign-gson 扩展的例子:
- static class Credentials {
- final String user_name;
- final String password;
- Credentials(String user_name, String password) {
- this.user_name = user_name;
- this.password = password;
- }
- }
- interface LoginClient {
- @RequestLine("POST /")
- void login(Credentials creds);
- }
- ...
- LoginClient client = Feign.builder()
- .encoder(new GsonEncoder())
- .target(LoginClient.class, "https://foo.com");
- client.login(new Credentials("denominator", "secret"));
@Body templates
@Body
注解申明一个请求体模板,模板中可以带有参数,与方法中 @Param
注解申明的参数相匹配,使用方法如下
- interface LoginClient {
- @RequestLine("POST /")
- @Headers("Content-Type: application/xml")
- @Body("<login \"user_name\"=\"{user_name}\" \"password\"=\"{password}\"/>")
- void xml(@Param("user_name") String user, @Param("password") String password);
- @RequestLine("POST /")
- @Headers("Content-Type: application/json")
- // json curly braces must be escaped!
- // 这里JSON格式需要的花括号居然需要转码,有点蛋疼了。
- @Body("%7B\"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D")
- void json(@Param("user_name") String user, @Param("password") String password);
- }
- ...
- // <login "user_name"="denominator" "password"="secret"/>
- client.xml("denominator", "secret");
- // {"user_name": "denominator", "password": "secret"}
- client.json("denominator", "secret");
Headers
Feign
支持给请求的api设置或者请求的客户端设置请求头
给API设置请求头
- 使用
@Headers
设置静态请求头
// 给BaseApi中的所有方法设置Accept请求头
@Headers("Accept: application/json")
interface BaseApi<V> {
// 单独给put方法设置Content-Type请求头
@Headers("Content-Type: application/json")
@RequestLine("PUT /api/{key}")
void put(@Param("key") String, V value);
}
- 设置动态值的请求头
@RequestLine("POST /")
@Headers("X-Ping: {token}")
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
注解,如下:
// @HeaderMap 注解设置的请求头优先于其他方式设置的
@RequestLine("POST /")
void post(@HeaderMap Map<String, Object> headerMap);
给Target设置请求头
有时我们需要在一个API实现中根据不同的endpoint来传入不同的Header,这个时候我们可以使用自定义的RequestInterceptor 或 Target来实现.
通过自定义的 RequestInterceptor 来实现请查看 Request Interceptors 章节.
下面是一个通过自定义Target来实现给每个Target设置安全校验信息Header的例子:
static class DynamicAuthTokenTarget<T> implements Target<T> {
public DynamicAuthTokenTarget(Class<T> clazz,
UrlAndTokenProvider provider,
ThreadLocal<String> requestIdProvider);
...
@Override
public Request apply(RequestTemplate input) {
TokenIdAndPublicURL urlAndToken = provider.get();
if (input.url().indexOf("http") != 0) {
input.insert(0, urlAndToken.publicURL);
}
input.header("X-Auth-Token", urlAndToken.tokenId);
input.header("X-Request-ID", requestIdProvider.get());
return input.request();
}
}
...
Bank bank = Feign.builder()
.target(new DynamicAuthTokenTarget(Bank.class, provider, requestIdProvider));
这种方法的实现依赖于给Feign
客户端设置的自定义的RequestInterceptor 或 Target。可以被用来给一个客户端的所有api请求设置请求头。比如说可是被用来在header中设置身份校验信息。这些方法是在线程执行api请求的时候才会执行,所以是允许在运行时根据上下文来动态设置header的。
比如说可以根据线程本地存储(thread-local storage)来为不同的线程设置不同的请求头。
高级用法
Base APIS
有些请求中的一些方法是通用的,但是可能会有不同的参数类型或者返回类型,这个时候可以这么用:
// 通用API
interface BaseAPI {
@RequestLine("GET /health")
String health();
@RequestLine("GET /all")
List<Entity> all();
}
// 继承通用API
interface CustomAPI extends BaseAPI {
@RequestLine("GET /custom")
String custom();
}
// 各种类型有相同的表现形式,定义一个统一的API
@Headers("Accept: application/json")
interface BaseApi<V> {
@RequestLine("GET /api/{key}")
V get(@Param("key") String key);
@RequestLine("GET /api")
List<V> list();
@Headers("Content-Type: application/json")
@RequestLine("PUT /api/{key}")
void put(@Param("key") String key, V value);
}
// 根据不同的类型来继承
interface FooApi extends BaseApi<Foo> { }
interface BarApi extends BaseApi<Bar> { }
Logging
你可以通过设置一个 Logger
来记录http消息,如下:
GitHub github = Feign.builder()
.decoder(new GsonDecoder())
.logger(new Logger.JavaLogger().appendToFile("logs/http.log"))
.logLevel(Logger.Level.FULL)
.target(GitHub.class, "https://api.github.com");
也可以参考上面的 SLF4J 章节的说明
Request Interceptors
当你希望修改所有的的请求的时候,你可以使用Request Interceptors。比如说,你作为一个中介,你可能需要为每个请求设置 X-Forwarded-For
static class ForwardedForInterceptor implements RequestInterceptor {
@Override public void apply(RequestTemplate template) {
template.header("X-Forwarded-For", "origin.host.com");
}
}
...
Bank bank = Feign.builder()
.decoder(accountDecoder)
.requestInterceptor(new ForwardedForInterceptor())
.target(Bank.class, "https://api.examplebank.com");
或者,你可能需要实现Basic Auth,这里有一个内置的基础校验拦截器 BasicAuthRequestInterceptor
Bank bank = Feign.builder()
.decoder(accountDecoder)
.requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.target(Bank.class, "https://api.examplebank.com");
Custom @Param Expansion
在使用 @Param
注解给模板中的参数设值的时候,默认的是使用的对象的 toString()
方法的值,通过声明 自定义的Param.Expander
,用户可以控制其行为,比如说格式化 Date
类型的值:
// 通过设置 @Param 的 expander 为 DateToMillis.class 可以定义Date类型的值
@RequestLine("GET /?since={date}")
Result list(@Param(value = "date", expander = DateToMillis.class) Date date);
Dynamic Query Parameters
动态查询参数支持,通过使用 @QueryMap
可以允许动态传入请求参数,如下:
@RequestLine("GET /find")
V find(@QueryMap Map<String, Object> queryMap);
Static and Default Methods
如果你使用的是JDK 1.8+ 的话,那么你可以给接口设置统一的默认方法和静态方法,这个事JDK8的新特性,如下:
interface GitHub {
@RequestLine("GET /repos/{owner}/{repo}/contributors")
List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
@RequestLine("GET /users/{username}/repos?sort={sort}")
List<Repo> repos(@Param("username") String owner, @Param("sort") String sort);
default List<Repo> repos(String owner) {
return repos(owner, "full_name");
}
/**
* Lists all contributors for all repos owned by a user.
*/
default List<Contributor> contributors(String user) {
MergingContributorList contributors = new MergingContributorList();
for(Repo repo : this.repos(owner)) {
contributors.addAll(this.contributors(user, repo.getName()));
}
return contributors.mergeResult();
}
static GitHub connect() {
return Feign.builder()
.decoder(new GsonDecoder())
.target(GitHub.class, "https://api.github.com");
}
}
Feign api调用方式的更多相关文章
- Azure Mobile Services的REST API调用方式和自定义API
Azure Mobile Services(移动服务)是微软在Azure平台中提供的一种跨平台的移动应用后端服务,即移动后端即服务.支持.NET和JavaScript(Node.js)写后端代码:支持 ...
- SpringBoot之Feign调用方式比较
一:事发原因 两个东家都使用SpringCloud,巴拉巴拉用上了Spring全家桶,从eureka到ribbon,从ribbon到feign,从feign到hystrix,然后在使用feign的时候 ...
- Saltstack的API接口与调用方式
saltstack看起来是成为一个大规模自己主动化运维和云计算管理的一个框架,类似于SDK,并非像puppet仅仅成为一个工具.基于良好设计的API和清楚的思路,让salt的二次开发变得非常easy ...
- Feign服务调用请求方式及参数总结
前言 最近做微服务架构的项目,在用feign来进行服务间的调用.在互调的过程中,难免出现问题,根据错误总结了一下,主要是请求方式的错误和接参数的错误造成的.在此进行一下总结记录.以下通过分为三种情况说 ...
- 小D课堂 - 新版本微服务springcloud+Docker教程_4-06 Feign核心源码解读和服务调用方式ribbon和Feign选择
笔记 6.Feign核心源码解读和服务调用方式ribbon和Feign选择 简介: 讲解Feign核心源码解读和 服务间的调用方式ribbon.feign选择 ...
- 小D课堂 - 新版本微服务springcloud+Docker教程_4-05 微服务调用方式之feign 实战 订单调用商品服务
笔记 5.微服务调用方式之feign 实战 订单调用商品服务 简介:改造电商项目 订单服务 调用商品服务获取商品信息 Feign: 伪RPC客户端(本质还是用http) ...
- SpringCloud(5)---Feign服务调用
SpringCloud(5)---Feign服务调用 上一篇写了通过Ribbon进行服务调用,这篇其它都一样,唯一不一样的就是通过Feign进行服务调用. 注册中心和商品微服务不变,和上篇博客一样,具 ...
- Spring Cloud Alibaba(8)---Feign服务调用
Feign服务调用 有关Spring Cloud Alibaba之前写过五篇文章,这篇也是在上面项目的基础上进行开发. Spring Cloud Alibaba(1)---入门篇 Spring Clo ...
- Vue.js——使用$.ajax和vue-resource实现OAuth的注册、登录、注销和API调用
概述 上一篇我们介绍了如何使用vue resource处理HTTP请求,结合服务端的REST API,就能够很容易地构建一个增删查改应用.这个应用始终遗留了一个问题,Web App在访问REST AP ...
随机推荐
- win10 ubuntu 同一硬盘双系统安装和启动设置
1.了解启动的顺序 电脑开机---> BIOS 设置 ----> 硬盘(MBR)/ GPT格式里的ESP分区 ---> (UEFI/GRUB)目录里的 *****.efi -- ...
- 2017.4.4 TCP/IP三次握手,四次挥手
之前在电话面试的时候,被问到,所以找到一个超级容易理解的图片,自己保存,也算分享.
- (19)jQuery操作文本和属性
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>jq ...
- C++学习(二十四)(C语言部分)之 结构体1
1.结构体 存放多个不同类型的数据 但是是相关联的 数组 存放多个相同类型的数据 结构体是存放多个相关联的不同类型的数组 struct 定义一个结构体类型 自定义类型 2.结构体定义方式 定义类型最通 ...
- PS学习之合成特效:被风沙侵蚀的动物们
素材 大象 尘埃 裂纹 沙子 土地 正式操作: 打开PS 新建一个文件 选国际标准纸张 给分辨率为72(分辨率越大越占内存) 然后确定 将图片旋转90度(图像——旋转——(顺/逆)90度) 下面选 ...
- 【BZOJ3244】【UOJ#122】【NOI2013]树的计数
NOI都是酱的题怎么玩啊,哇.jpg 原题: 我们知道一棵有根树可以进行深度优先遍历(DFS)以及广度优先遍历(BFS)来生成这棵树的DFS序以及BFS序.两棵不同的树的DFS序有可能相同,并且它们的 ...
- python实现单链表的翻转
#!/usr/bin/env python #coding = utf-8 class Node: def __init__(self,data=None,next = None): ...
- linux面试题(自己添加了一些注释说明)
1.linux如何挂在windows下的共享目录 首先需要在Windows中创建一个文件夹用来共享,例如下面就是server是用来共享的,貌似在哪个位置创建都可以,我是在d盘创建的 1 mount.c ...
- for in和for of
- linux centos6 yum 安装lamp
centos 6.5 1.yum安装和源代码编译在使用的时候没啥区别,但是安装的过程就大相径庭了,yum只需要3个命令就可以完成,源代码需要13个包,还得加压编译,步骤很麻烦,而且当做有时候会出错,源 ...