Java探索之Feign入門使用詳解
一,簡介
Feign使得 Java HTTP 客戶端編寫更方便。Feign 靈感來源于Retrofit、JAXRS-2.0和WebSocket。Feign最初是為了降低統(tǒng)一綁定Denominator到HTTP API的復(fù)雜度,不區(qū)分是否支持Restful。Feign旨在通過最少的資源和代碼來實現(xiàn)和HTTP API的連接。通過可定制的解碼器和錯誤處理,可以編寫任意的HTTP API。
Maven依賴:
<!-- 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 服務(wù)的java客服端。你也可以直接使用 Apache HttpClient 來實現(xiàn)。但是 Feign 的目的是盡量的減少資源和代碼來實現(xiàn)和 HTTP API 的連接。通過自定義的編碼解碼器以及錯誤處理,你可以編寫任何基于文本的 HTTP API。
Feign工作機制
Feign通過注解注入一個模板化請求進行工作。只需在發(fā)送之前關(guān)閉它,參數(shù)就可以被直接的運用到模板中。然而這也限制了Feign,只支持文本形式的API,它在響應(yīng)請求等方面極大的簡化了系統(tǒng)。同時,它也是十分容易進行單元測試的。
三,Feign使用簡介
3.1,基本用法
基本的使用如下所示,一個對于canonical Retrofit sample的適配。
interface GitHub { // RequestLine注解聲明請求方法和請求地址,可以允許有查詢參數(shù) @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() 來構(gòu)造一個擁有你自己組件的API接口。如下:
interface Bank { @RequestLine("POST /account/{id}") Account getAccountInfo(@Param("id") String id); } ... // AccountDecoder() 是自己實現(xiàn)的一個Decoder Bank bank = Feign.builder().decoder(new AccountDecoder()).target(Bank.class, https://api.examplebank.com);
3.3,多種接口
Feign可以提供多種API接口,這些接口都被定義為 Target<T> (默認的實現(xiàn)是 HardCodedTarget<T>), 它允許在執(zhí)行請求前動態(tài)發(fā)現(xiàn)和裝飾該請求。
舉個例子,下面的這個模式允許使用當(dāng)前url和身份驗證token來裝飾每個發(fā)往身份驗證中心服務(wù)的請求。
CloudDNS cloudDNS = Feign.builder().target(new CloudIdentityTarget<CloudDNS>(user, apiKey));
示例
Feign 包含了 GitHub 和 Wikipedia 客戶端的實現(xiàn)樣例.相似的項目也同樣在實踐中運用了Feign。尤其是它的示例后臺程序。
四,Feign集成模塊
Feign 可以和其他的開源工具集成工作。你可以將這些開源工具集成到 Feign 中來。目前已經(jīng)有的一些模塊如下:
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, 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>
4.2,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>
4.3,Sax
SaxDecoder 用于解析XML,并兼容普通JVM和Android。下面是一個配置sax來解析響應(yīng)的例子:
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>
4.4,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>
4.5,JAX-RS
JAXRSContract 使用 JAX-RS 規(guī)范重寫覆蓋了默認的注解處理。下面是一個使用 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>
4.5,OkHttp
OkHttpClient 使用 OkHttp 來發(fā)送 Feign 的請求,OkHttp 支持 SPDY (SPDY是Google開發(fā)的基于TCP的傳輸層協(xié)議,用以最小化網(wǎng)絡(luò)延遲,提升網(wǎng)絡(luò)速度,優(yōu)化用戶的網(wǎng)絡(luò)使用體驗),并有更好的控制http請求。
要讓 Feign 使用 OkHttp ,你需要將 OkHttp 加入到你的環(huán)境變量中區(qū),然后配置 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>
4.6,Ribbon
RibbonClient 重寫了 Feign 客戶端的對URL的處理,其添加了 智能路由以及一些其他由Ribbon提供的彈性功能。
集成Ribbon需要你將ribbon的客戶端名稱當(dāng)做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>
4.7,Hystrix
HystrixFeign 配置了 Hystrix 提供的熔斷機制。
要在 Feign 中使用 Hystrix ,你需要添加Hystrix模塊到你的環(huán)境變量,然后使用 HystrixFeign 來構(gòu)造你的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>
4.8,SLF4J
SLF4JModule 允許你使用 SLF4J 作為 Feign 的日志記錄模塊,這樣你就可以輕松的使用 Logback, Log4J , 等 來記錄你的日志.
要在 Feign 中使用 SLF4J ,你需要添加SLF4J模塊和對應(yīng)的日志記錄實現(xiàn)模塊(比如Log4J)到你的環(huán)境變量,然后配置 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 組成
5.1,Decoders
Feign.builder() 允許你自定義一些額外的配置,比如說如何解碼一個響應(yīng)。假如有接口方法返回的消息不是 Response, String, byte[] 或者 void 類型的,那么你需要配置一個非默認的解碼器。
下面是一個配置使用JSON解碼器(使用的是feign-gson擴展)的例子:
GitHub github = Feign.builder() .decoder(new GsonDecoder()) .target(GitHub.class, https://api.github.com);
假如你想在將響應(yīng)傳遞給解碼器處理前做一些額外的處理,那么你可以使用mapAndDecode方法。一個用例就是使用jsonp服務(wù)的時候:
// 貌似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
發(fā)送一個Post請求最簡單的方法就是傳遞一個 String 或者 byte[] 類型的參數(shù)了。你也許還需添加一個Content-Type請求頭,如下:
interface LoginClient { @RequestLine("POST /") @Headers("Content-Type: application/json") void login(String content); } ... client.login("{\"user_name\": \"denominator\", \"password\": \"secret\"}");
通過配置一個解碼器,你可以發(fā)送一個安全類型的請求體,如下是一個使用 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"));
5.3,@Body templates
@Body注解申明一個請求體模板,模板中可以帶有參數(shù),與方法中 @Param 注解申明的參數(shù)相匹配,使用方法如下:
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格式需要的花括號居然需要轉(zhuǎn)碼,有點蛋疼了。 @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設(shè)置或者請求的客戶端設(shè)置請求頭,如下:
給API設(shè)置請求頭
使用 @Headers 設(shè)置靜態(tài)請求頭
// 給BaseApi中的所有方法設(shè)置Accept請求頭 @Headers("Accept: application/json") interface BaseApi<V> { // 單獨給put方法設(shè)置Content-Type請求頭 @Headers("Content-Type: application/json") @RequestLine("PUT /api/{key}") void put(@Param("key") String, V value); }
設(shè)置動態(tài)值的請求頭
@RequestLine("POST /") @Headers("X-Ping: {token}") void post(@Param("token") String token);
設(shè)置key和value都是動態(tài)的請求頭
有些API需要根據(jù)調(diào)用時動態(tài)確定使用不同的請求頭(e.g. custom metadata header fields such as “x-amz-meta-“ or “x-goog-meta-“),
這時候可以使用 @HeaderMap 注解,如下:
// @HeaderMap 注解設(shè)置的請求頭優(yōu)先于其他方式設(shè)置的 @RequestLine("POST /") void post(@HeaderMap Map<String, Object> headerMap);
給Target設(shè)置請求頭
有時我們需要在一個API實現(xiàn)中根據(jù)不同的endpoint來傳入不同的Header,這個時候我們可以使用自定義的RequestInterceptor 或 Target來實現(xiàn).
通過自定義的 RequestInterceptor 來實現(xiàn)請查看 Request Interceptors 章節(jié).
下面是一個通過自定義Target來實現(xiàn)給每個Target設(shè)置安全校驗信息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));
這種方法的實現(xiàn)依賴于給Feign 客戶端設(shè)置的自定義的RequestInterceptor 或 Target??梢员挥脕斫o一個客戶端的所有api請求設(shè)置請求頭。比如說可是被用來在header中設(shè)置身份校驗信息。這些方法是在線程執(zhí)行api請求的時候才會執(zhí)行,所以是允許在運行時根據(jù)上下文來動態(tài)設(shè)置header的。
比如說可以根據(jù)線程本地存儲(thread-local storage)來為不同的線程設(shè)置不同的請求頭。
六,高級用法
6.1,Base APIS
有些請求中的一些方法是通用的,但是可能會有不同的參數(shù)類型或者返回類型,這個時候可以這么用:
// 通用API interface BaseAPI { @RequestLine("GET /health") String health(); @RequestLine("GET /all") List<Entity> all(); } // 繼承通用API interface CustomAPI extends BaseAPI { @RequestLine("GET /custom") String custom(); } // 各種類型有相同的表現(xiàn)形式,定義一個統(tǒng)一的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); } // 根據(jù)不同的類型來繼承 interface FooApi extends BaseApi<Foo> { } interface BarApi extends BaseApi<Bar> { }
6.2,Logging
你可以通過設(shè)置一個 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 章節(jié)的說明
6.3,Request Interceptors
當(dāng)你希望修改所有的的請求的時候,你可以使用Request Interceptors。比如說,你作為一個中介,你可能需要為每個請求設(shè)置 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);
或者,你可能需要實現(xiàn)Basic Auth,這里有一個內(nèi)置的基礎(chǔ)校驗攔截器
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 注解給模板中的參數(shù)設(shè)值的時候,默認的是使用的對象的 toString() 方法的值,通過聲明 自定義的Param.Expander,用戶可以控制其行為,比如說格式化 Date 類型的值:
// 通過設(shè)置 @Param 的 expander 為 DateToMillis.class 可以定義Date類型的值 @RequestLine("GET /?since={date}") Result list(@Param(value = "date", expander = DateToMillis.class) Date date);
6.5,Dynamic Query Parameters
動態(tài)查詢參數(shù)支持,通過使用 @QueryMap 可以允許動態(tài)傳入請求參數(shù),如下:
@RequestLine("GET /find") V find(@QueryMap Map<String, Object> queryMap);
6.6,Static and Default Methods
如果你使用的是JDK 1.8+ 的話,那么你可以給接口設(shè)置統(tǒng)一的默認方法和靜態(tài)方法,這個事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"); } }
總結(jié)
以上就是本文關(guān)于Java探索之Feign入門使用詳解的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站:Java編程幾個循環(huán)實例代碼分享、Java面向?qū)ο缶幊蹋ǚ庋b/繼承/多態(tài))實例解析等,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關(guān)文章
spring boot udp或者tcp接收數(shù)據(jù)的實例詳解
這篇文章主要介紹了spring boot udp或者tcp接收數(shù)據(jù),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12基于jdk動態(tài)代理和cglib動態(tài)代理實現(xiàn)及區(qū)別說明
這篇文章主要介紹了基于jdk動態(tài)代理和cglib動態(tài)代理實現(xiàn)及區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-0520秒教你學(xué)會java?List函數(shù)排序操作示例
這篇文章主要為大家介紹了20秒教你學(xué)會List函數(shù)排序操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09Springboot傳輸數(shù)據(jù)時日期格式化問題
這篇文章主要介紹了Springboot傳輸數(shù)據(jù)時日期格式化問題,本文通過示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09