Java探索之Feign⼊门使⽤详解
⼀,简介
Feign使得 Java HTTP 客户端编写更⽅便。Feign 灵感来源于Retrofit、JAXRS-2.0和WebSocket。Feign最初是为了降低统⼀绑定Denominator到HTTP API的复杂度,不区分是否⽀持Restful。Feign旨在通过最少的资源和代码来实现和HTTP API的连接。通过可定制的解码器和错误处理,可以编写任意的HTTP API。
Maven依赖:
<!-- mvnrepository/artifact/comflix.feign/feign-core -->
<dependency>
<groupId>comflix.feign</groupId>
<artifactId>feign-core</artifactId>
<version>8.18.0</version>
<scope>runtime</scope>
</dependency>
⼆,为什么选择Feign⽽不是其他
你可以使⽤ Jersey 和 CXF 这些来写⼀个 Rest 或 SOAP 服务的java客服端。你也可以直接使⽤ Apache HttpClient 来实现。但是 Feign 的⽬的是尽量的减少资源和代码来实现和 HTTP API 的连接。通过⾃定义的编码解码器以及错误处理,你可以编写任何基于⽂本的 HTTP API。
Feign⼯作机制
Feign通过注解注⼊⼀个模板化请求进⾏⼯作。只需在发送之前关闭它,参数就可以被直接的运⽤到模板中。然⽽这也限制了Feign,只⽀持⽂本形式的API,它在响应请求等⽅⾯极⼤的简化了系统。同时,它也是⼗分容易进⾏单元测试的。
三,Feign使⽤简介
3.1,基本⽤法
如何配置maven环境变量基本的使⽤如下所⽰,⼀个对于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 args) {
GitHub github = Feign.builder()
.
decoder(new GsonDecoder())
.target(GitHub.class, "api.github");
// Fetch and print a list of the contributors to this library.
List<Contributor> contributors = ibutors("OpenFeign", "feign");
for (Contributor contributor : contributors) {
System.out.println(contributor.login + " (" + ibutions + ")");
}
}
3.2,⾃定义
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, amplebank);
3.3,多种接⼝
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 中来。⽬前已经有的⼀些模块如下:
4.1,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, api.github);
Maven依赖:
<!-- mvnrepository/artifact/comflix.feign/feign-gson -->
<dependency>
<groupId>comflix.feign</groupId>
<artifactId>feign-gson</artifactId>
<version>8.18.0</version>
</dependency>
4.2,Jackson
Jackson 包含了⼀个编码器和⼀个解码器,这个可以被⽤于JSON格式的API。
添加 JacksonEncoder 以及 JacksonDecoder 到你的 Feign.Builder 中,如下:
GitHub github = Feign.builder()
.encoder(new JacksonEncoder())
.decoder(new JacksonDecoder())
.target(GitHub.class, api.github);
Maven依赖:
<!-- mvnrepository/artifact/comflix.feign/feign-gson -->
<dependency>
<groupId>comflix.feign</groupId>
<artifactId>feign-jackson</artifactId>
<version>8.18.0</version>
</dependency>
4.3,Sax
SaxDecoder ⽤于解析XML,并兼容普通JVM和Android。下⾯是⼀个配置sax来解析响应的例⼦:
Maven依赖:
<dependency>
<groupId>comflix.feign</groupId>
<artifactId>feign-sax</artifactId>
<version>8.18.0</version>
</dependency>
4.4,JAXB
JAXB 包含了⼀个编码器和⼀个解码器,这个可以被⽤于XML格式的API。
添加 JAXBEncoder 以及 JAXBDecoder 到你的 Feign.Builder 中,如下:
api = Feign.builder()
.encoder(new JAXBEncoder())
.target(Api.class, apihost);
Maven依赖:
<!-- mvnrepository/artifact/comflix.feign/feign-gson -->
<dependency>
<groupId>comflix.feign</groupId>
<artifactId>feign-jaxb</artifactId>
<version>8.18.0</version>
</dependency>
4.5,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, api.github);
Maven依赖:
<!-- mvnrepository/artifact/comflix.feign/feign-gson -->
<dependency>
<groupId>comflix.feign</groupId>
<artifactId>feign-jaxrs</artifactId>
<version>8.18.0</version>
</dependency>
4.5,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, "api.github");
Maven依赖:
<!-- mvnrepository/artifact/comflix.feign/feign-gson -->
<dependency>
<groupId>comflix.feign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>8.18.0</version>
</dependency>
4.6,Ribbon
RibbonClient 重写了 Feign 客户端的对URL的处理,其添加了智能路由以及⼀些其他由Ribbon提供的弹性功能。
集成Ribbon需要你将ribbon的客户端名称当做url的host部分来传递,如下:
// myAppProd是你的ribbon client name
MyService api = Feign.builder().ate()).target(MyService.class, "myAppProd");
Maven依赖:
<!-- mvnrepository/artifact/comflix.feign/feign-gson -->
<dependency>
<groupId>comflix.feign</groupId>
<artifactId>feign-ribbon</artifactId>
<version>8.18.0</version>
</dependency>
4.7,Hystrix
HystrixFeign 配置了 Hystrix 提供的熔断机制。
要在 Feign 中使⽤ Hystrix ,你需要添加Hystrix模块到你的环境变量,然后使⽤ HystrixFeign 来构造你的API:
MyService api = HystrixFeign.builder().target(MyService.class, "myAppProd");
<!-- mvnrepository/artifact/comflix.feign/feign-gson -->
<dependency>
<groupId>comflix.feign</groupId>
<artifactId>feign-hystrix</artifactId>
<version>8.18.0</version>
</dependency>
4.8,SLF4J
SLF4JModule 允许你使⽤ SLF4J 作为 Feign 的⽇志记录模块,这样你就可以轻松的使⽤ Logback, Log4J , 等来记录你的⽇志.
要在 Feign 中使⽤ SLF4J ,你需要添加SLF4J模块和对应的⽇志记录实现模块(⽐如Log4J)到你的环境变量,然后配置 Feign 使⽤Slf4jLogger :
GitHub github = Feign.builder()
.logger(new Slf4jLogger())
.target(GitHub.class, "api.github");
Maven依赖:
<!-- mvnrepository/artifact/comflix.feign/feign-gson -->
<dependency>
<groupId>comflix.feign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>8.18.0</version>
</dependency>
五,Feign 组成
5.1,Decoders
Feign.builder() 允许你⾃定义⼀些额外的配置,⽐如说如何解码⼀个响应。假如有接⼝⽅法返回的消息不是 Response, String, byte[] 或者 void 类型的,那么你需要配置⼀个⾮默认的解码器。
下⾯是⼀个配置使⽤JSON解码器(使⽤的是feign-gson扩展)的例⼦:
GitHub github = Feign.builder()
.decoder(new GsonDecoder())
.target(GitHub.class, api.github);
假如你想在将响应传递给解码器处理前做⼀些额外的处理,那么你可以使⽤mapAndDecode⽅法。⼀个⽤例就是使⽤jsonp服务的时候:
// 貌似1.8.0版本中沒有mapAndDecode这个⽅法。。。
JsonpApi jsonpApi = Feign.builder()
.mapAndDecode((response, type) -> jsopUnwrap(response, type), new GsonDecoder())
.target(JsonpApi.class, some-jsonp-api);
5.2,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, "foo");
client.login(new Credentials("denominator", "secret"));
5.3,@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);
}
...
client.json("denominator", "secret"); // {"user_name": "denominator", "password": "secret"}
5.4,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);