一,簡介
Feign使得 Java HTTP 客戶端編寫更方便。Feign 靈感來源于Retrofit、JAXRS-2.0和WebSocket。Feign最初是為了降低統一綁定Denominator到HTTP API的復雜度,不區分是否支持Restful。Feign旨在通過最少的資源和代碼來實現和HTTP API的連接。通過可定制的解碼器和錯誤處理,可以編寫任意的HTTP API。
Maven依賴:
1
2
3
4
5
6
7
|
<!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-core --> < dependency > < groupId >com.netflix.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,基本用法
基本的使用如下所示,一個對于canonical Retrofit sample的適配。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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 + ")" ); } } |
3.2,自定義
Feign 有許多可以自定義的方面。舉個簡單的例子,你可以使用 Feign.builder() 來構造一個擁有你自己組件的API接口。如下:
1
2
3
4
5
6
7
|
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); |
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 中, 如下:
1
2
3
4
5
|
GsonCodec codec = new GsonCodec(); GitHub github = Feign.builder() .encoder( new GsonEncoder()) .decoder( new GsonDecoder()) .target(GitHub. class , https: //api.github.com); |
Maven依賴:
1
2
3
4
5
6
|
<!-- 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 > |
4.2,Jackson
Jackson 包含了一個編碼器和一個解碼器,這個可以被用于JSON格式的API。
添加 JacksonEncoder 以及 JacksonDecoder 到你的 Feign.Builder 中, 如下:
1
2
3
4
|
GitHub github = Feign.builder() .encoder( new JacksonEncoder()) .decoder( new JacksonDecoder()) .target(GitHub. class , https: //api.github.com); |
Maven依賴:
1
2
3
4
5
6
|
<!-- 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> |
4.3,Sax
SaxDecoder 用于解析XML,并兼容普通JVM和Android。下面是一個配置sax來解析響應的例子:
api = Feign.builder()
.decoder(SAXDecoder.builder()
.registerContentHandler(UserIdHandler.class)
.build())
.target(Api.class, https://apihost);
Maven依賴:
1
2
3
4
5
|
<dependency> <groupId>com.netflix.feign</groupId> <artifactId>feign-sax</artifactId> <version> 8.18 . 0 </version> </dependency> |
4.4,JAXB
JAXB 包含了一個編碼器和一個解碼器,這個可以被用于XML格式的API。
添加 JAXBEncoder 以及 JAXBDecoder 到你的 Feign.Builder 中, 如下:
1
2
3
4
|
api = Feign.builder() .encoder( new JAXBEncoder()) .decoder( new JAXBDecoder()) .target(Api. class , https: //apihost); |
Maven依賴:
1
2
3
4
5
6
|
<!-- 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 > |
4.5,JAX-RS
JAXRSContract 使用 JAX-RS 規范重寫覆蓋了默認的注解處理。下面是一個使用 JAX-RS 的例子:
1
2
3
4
5
6
7
8
|
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依賴:
1
2
3
4
5
6
|
<!-- 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 > |
4.5,OkHttp
OkHttpClient 使用 OkHttp 來發送 Feign 的請求,OkHttp 支持 SPDY (SPDY是Google開發的基于TCP的傳輸層協議,用以最小化網絡延遲,提升網絡速度,優化用戶的網絡使用體驗),并有更好的控制http請求。
要讓 Feign 使用 OkHttp ,你需要將 OkHttp 加入到你的環境變量中區,然后配置 Feign 使用 OkHttpClient,如下:
1
2
3
4
5
6
7
8
9
10
|
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> |
4.6,Ribbon
RibbonClient 重寫了 Feign 客戶端的對URL的處理,其添加了 智能路由以及一些其他由Ribbon提供的彈性功能。
集成Ribbon需要你將ribbon的客戶端名稱當做url的host部分來傳遞,如下:
1
2
3
4
5
6
7
8
9
|
// 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> |
4.7,Hystrix
HystrixFeign 配置了 Hystrix 提供的熔斷機制。
要在 Feign 中使用 Hystrix ,你需要添加Hystrix模塊到你的環境變量,然后使用 HystrixFeign 來構造你的API:
1
2
3
4
5
6
7
8
|
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> |
4.8,SLF4J
SLF4JModule 允許你使用 SLF4J 作為 Feign 的日志記錄模塊,這樣你就可以輕松的使用 Logback, Log4J , 等 來記錄你的日志.
要在 Feign 中使用 SLF4J ,你需要添加SLF4J模塊和對應的日志記錄實現模塊(比如Log4J)到你的環境變量,然后配置 Feign使用Slf4jLogger :
1
2
3
4
5
6
7
8
9
10
|
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 組成
5.1,Decoders
Feign.builder() 允許你自定義一些額外的配置,比如說如何解碼一個響應。假如有接口方法返回的消息不是 Response, String, byte[] 或者 void 類型的,那么你需要配置一個非默認的解碼器。
下面是一個配置使用JSON解碼器(使用的是feign-gson擴展)的例子:
1
2
3
|
GitHub github = Feign.builder() .decoder( new GsonDecoder()) .target(GitHub. class , https: //api.github.com); |
假如你想在將響應傳遞給解碼器處理前做一些額外的處理,那么你可以使用mapAndDecode方法。一個用例就是使用jsonp服務的時候:
1
2
3
4
|
// 貌似1.8.0版本中沒有mapAndDecode這個方法。。。 JsonpApi jsonpApi = Feign.builder() .mapAndDecode((response, type) -> jsopUnwrap(response, type), new GsonDecoder()) .target(JsonpApi. class , https: //some-jsonp-api.com); |
5.2,Encoders
發送一個Post請求最簡單的方法就是傳遞一個 String 或者 byte[] 類型的參數了。你也許還需添加一個Content-Type請求頭,如下:
1
2
3
4
5
6
7
|
interface LoginClient { @RequestLine ( "POST /" ) @Headers ( "Content-Type: application/json" ) void login(String content); } ... client.login( "{\"user_name\": \"denominator\", \"password\": \"secret\"}" ); |
通過配置一個解碼器,你可以發送一個安全類型的請求體,如下是一個使用 feign-gson 擴展的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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" )); |
5.3,@Body templates
@Body注解申明一個請求體模板,模板中可以帶有參數,與方法中 @Param 注解申明的參數相匹配,使用方法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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.xml( "denominator" , "secret" ); // <login "user_name"="denominator" "password"="secret"/> client.json( "denominator" , "secret" ); // {"user_name": "denominator", "password": "secret"} |
5.4,Headers
Feign 支持給請求的api設置或者請求的客戶端設置請求頭,如下:
給API設置請求頭
使用 @Headers 設置靜態請求頭
1
2
3
4
5
6
7
8
|
// 給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); } |
設置動態值的請求頭
1
2
3
|
@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 注解,如下:
1
2
3
|
// @HeaderMap 注解設置的請求頭優先于其他方式設置的 @RequestLine ( "POST /" ) void post( @HeaderMap Map<String, Object> headerMap); |
給Target設置請求頭
有時我們需要在一個API實現中根據不同的endpoint來傳入不同的Header,這個時候我們可以使用自定義的RequestInterceptor 或 Target來實現.
通過自定義的 RequestInterceptor 來實現請查看 Request Interceptors 章節.
下面是一個通過自定義Target來實現給每個Target設置安全校驗信息Header的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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)來為不同的線程設置不同的請求頭。
六,高級用法
6.1,Base APIS
有些請求中的一些方法是通用的,但是可能會有不同的參數類型或者返回類型,這個時候可以這么用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
// 通用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> { } |
6.2,Logging
你可以通過設置一個 Logger 來記錄http消息,如下:
1
2
3
4
5
|
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 章節的說明
6.3,Request Interceptors
當你希望修改所有的的請求的時候,你可以使用Request Interceptors。比如說,你作為一個中介,你可能需要為每個請求設置 X-Forwarded-For
1
2
3
4
5
6
7
8
9
10
|
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,這里有一個內置的基礎校驗攔截器
1
2
3
4
5
|
BasicAuthRequestInterceptor Bank bank = Feign.builder() .decoder(accountDecoder) .requestInterceptor( new BasicAuthRequestInterceptor(username, password)) .target(Bank. class , https: //api.examplebank.com); |
6.4,Custom @Param Expansion
在使用 @Param 注解給模板中的參數設值的時候,默認的是使用的對象的 toString() 方法的值,通過聲明 自定義的Param.Expander,用戶可以控制其行為,比如說格式化 Date 類型的值:
1
2
3
|
// 通過設置 @Param 的 expander 為 DateToMillis.class 可以定義Date類型的值 @RequestLine ( "GET /?since={date}" ) Result list( @Param (value = "date" , expander = DateToMillis. class ) Date date); |
6.5,Dynamic Query Parameters
動態查詢參數支持,通過使用 @QueryMap 可以允許動態傳入請求參數,如下:
1
2
|
@RequestLine("GET /find") V find(@QueryMap Map< String , Object> queryMap); |
6.6,Static and Default Methods
如果你使用的是JDK 1.8+ 的話,那么你可以給接口設置統一的默認方法和靜態方法,這個事JDK8的新特性,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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" ); } } |
總結
以上就是本文關于Java探索之Feign入門使用詳解的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/u012562943/article/details/78257900