Feign api调用方式
Feign使用簡(jiǎn)介
基本用法
基本的使用如下所示,一個(gè)對(duì)于canonical Retrofit sample的適配。
interface GitHub {// RequestLine注解聲明請(qǐng)求方法和請(qǐng)求地址,可以允許有查詢(xún)參數(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 + ")");} }?
自定義
Feign?有許多可以自定義的方面。舉個(gè)簡(jiǎn)單的例子,你可以使用?Feign.builder()?來(lái)構(gòu)造一個(gè)擁有你自己組件的API接口。如下:
interface Bank {@RequestLine("POST /account/{id}")Account getAccountInfo(@Param("id") String id); } ... // AccountDecoder() 是自己實(shí)現(xiàn)的一個(gè)Decoder Bank bank = Feign.builder().decoder(new AccountDecoder()).target(Bank.class, "https://api.examplebank.com");?
多種接口
Feign可以提供多種API接口,這些接口都被定義為?Target<T>?(默認(rèn)的實(shí)現(xiàn)是?HardCodedTarget<T>), 它允許在執(zhí)行請(qǐng)求前動(dòng)態(tài)發(fā)現(xiàn)和裝飾該請(qǐng)求。?
舉個(gè)例子,下面的這個(gè)模式允許使用當(dāng)前url和身份驗(yàn)證token來(lái)裝飾每個(gè)發(fā)往身份驗(yàn)證中心服務(wù)的請(qǐng)求。
?
示例
Feign?包含了?GitHub?和?Wikipedia?客戶(hù)端的實(shí)現(xiàn)樣例.相似的項(xiàng)目也同樣在實(shí)踐中運(yùn)用了Feign。尤其是它的示例后臺(tái)程序。
Feign集成模塊
Feign?可以和其他的開(kāi)源工具集成工作。你可以將這些開(kāi)源工具集成到?Feign?中來(lái)。目前已經(jīng)有的一些模塊如下:
Gson
Gson?包含了一個(gè)編碼器和一個(gè)解碼器,這個(gè)可以被用于JSON格式的API。?
添加?GsonEncoder?以及?GsonDecoder?到你的?Feign.Builder?中, 如下:
?
Maven依賴(lài):
<!-- 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?包含了一個(gè)編碼器和一個(gè)解碼器,這個(gè)可以被用于JSON格式的API。?
添加?JacksonEncoder?以及?JacksonDecoder?到你的?Feign.Builder?中, 如下:
?
Maven依賴(lài):
<!-- 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。下面是一個(gè)配置sax來(lái)解析響應(yīng)的例子:
api = Feign.builder().decoder(SAXDecoder.builder().registerContentHandler(UserIdHandler.class).build()).target(Api.class, "https://apihost");?
Maven依賴(lài):
<dependency><groupId>com.netflix.feign</groupId><artifactId>feign-sax</artifactId><version>8.18.0</version> </dependency>?
JAXB
JAXB?包含了一個(gè)編碼器和一個(gè)解碼器,這個(gè)可以被用于XML格式的API。?
添加?JAXBEncoder?以及?JAXBDecoder?到你的?Feign.Builder?中, 如下:
?
Maven依賴(lài):
<!-- 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 規(guī)范重寫(xiě)覆蓋了默認(rèn)的注解處理。下面是一個(gè)使用 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依賴(lài):
<!-- 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?來(lái)發(fā)送?Feign?的請(qǐng)求,OkHttp?支持?SPDY?(SPDY是Google開(kāi)發(fā)的基于TCP的傳輸層協(xié)議,用以最小化網(wǎng)絡(luò)延遲,提升網(wǎng)絡(luò)速度,優(yōu)化用戶(hù)的網(wǎng)絡(luò)使用體驗(yàn)),并有更好的控制http請(qǐng)求。?
要讓?Feign?使用?OkHttp?,你需要將?OkHttp?加入到你的環(huán)境變量中區(qū),然后配置?Feign?使用?OkHttpClient,如下:
?
Maven依賴(lài):
<!-- 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?重寫(xiě)了?Feign?客戶(hù)端的對(duì)URL的處理,其添加了 智能路由以及一些其他由Ribbon提供的彈性功能。?
集成Ribbon需要你將ribbon的客戶(hù)端名稱(chēng)當(dāng)做url的host部分來(lái)傳遞,如下:
?
Maven依賴(lài):
<!-- 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?提供的熔斷機(jī)制。?
要在?Feign?中使用?Hystrix?,你需要添加Hystrix模塊到你的環(huán)境變量,然后使用?HystrixFeign?來(lái)構(gòu)造你的API:
?
Maven依賴(lài):
<!-- 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?, 等 來(lái)記錄你的日志.?
要在?Feign?中使用?SLF4J?,你需要添加SLF4J模塊和對(duì)應(yīng)的日志記錄實(shí)現(xiàn)模塊(比如Log4J)到你的環(huán)境變量,然后配置?Feign使用Slf4jLogger?:
?
Maven依賴(lài):
<!-- 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()?允許你自定義一些額外的配置,比如說(shuō)如何解碼一個(gè)響應(yīng)。假如有接口方法返回的消息不是?Response,?String,?byte[]?或者?void?類(lèi)型的,那么你需要配置一個(gè)非默認(rèn)的解碼器。?
下面是一個(gè)配置使用JSON解碼器(使用的是feign-gson擴(kuò)展)的例子:
?
假如你想在將響應(yīng)傳遞給解碼器處理前做一些額外的處理,那么你可以使用mapAndDecode方法。一個(gè)用例就是使用jsonp服務(wù)的時(shí)候:
// 貌似1.8.0版本中沒(méi)有mapAndDecode這個(gè)方法。。。 JsonpApi jsonpApi = Feign.builder().mapAndDecode((response, type) -> jsopUnwrap(response, type), new GsonDecoder()).target(JsonpApi.class, "https://some-jsonp-api.com");?
Encoders
發(fā)送一個(gè)Post請(qǐng)求最簡(jiǎn)單的方法就是傳遞一個(gè)?String?或者?byte[]?類(lèi)型的參數(shù)了。你也許還需添加一個(gè)Content-Type請(qǐng)求頭,如下:
interface LoginClient {@RequestLine("POST /")@Headers("Content-Type: application/json")void login(String content); } ... client.login("{\"user_name\": \"denominator\", \"password\": \"secret\"}");?
通過(guò)配置一個(gè)解碼器,你可以發(fā)送一個(gè)安全類(lèi)型的請(qǐng)求體,如下是一個(gè)使用 feign-gson 擴(kuò)展的例子:
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注解申明一個(gè)請(qǐng)求體模板,模板中可以帶有參數(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格式需要的花括號(hào)居然需要轉(zhuǎn)碼,有點(diǎn)蛋疼了。@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?支持給請(qǐng)求的api設(shè)置或者請(qǐng)求的客戶(hù)端設(shè)置請(qǐng)求頭
給API設(shè)置請(qǐng)求頭
- 使用?@Headers?設(shè)置靜態(tài)請(qǐng)求頭
- 設(shè)置動(dòng)態(tài)值的請(qǐng)求頭
- 設(shè)置key和value都是動(dòng)態(tài)的請(qǐng)求頭?
有些API需要根據(jù)調(diào)用時(shí)動(dòng)態(tài)確定使用不同的請(qǐng)求頭(e.g. custom metadata header fields such as “x-amz-meta-” or “x-goog-meta-“),?
這時(shí)候可以使用?@HeaderMap?注解,如下:
給Target設(shè)置請(qǐng)求頭
有時(shí)我們需要在一個(gè)API實(shí)現(xiàn)中根據(jù)不同的endpoint來(lái)傳入不同的Header,這個(gè)時(shí)候我們可以使用自定義的RequestInterceptor 或 Target來(lái)實(shí)現(xiàn).?
通過(guò)自定義的 RequestInterceptor 來(lái)實(shí)現(xiàn)請(qǐng)查看?Request Interceptors?章節(jié).?
下面是一個(gè)通過(guò)自定義Target來(lái)實(shí)現(xiàn)給每個(gè)Target設(shè)置安全校驗(yàn)信息Header的例子:
這種方法的實(shí)現(xiàn)依賴(lài)于給Feign?客戶(hù)端設(shè)置的自定義的RequestInterceptor 或 Target。可以被用來(lái)給一個(gè)客戶(hù)端的所有api請(qǐng)求設(shè)置請(qǐng)求頭。比如說(shuō)可是被用來(lái)在header中設(shè)置身份校驗(yàn)信息。這些方法是在線程執(zhí)行api請(qǐng)求的時(shí)候才會(huì)執(zhí)行,所以是允許在運(yùn)行時(shí)根據(jù)上下文來(lái)動(dòng)態(tài)設(shè)置header的。?
比如說(shuō)可以根據(jù)線程本地存儲(chǔ)(thread-local storage)來(lái)為不同的線程設(shè)置不同的請(qǐng)求頭。
高級(jí)用法
Base APIS
有些請(qǐng)求中的一些方法是通用的,但是可能會(huì)有不同的參數(shù)類(lèi)型或者返回類(lèi)型,這個(gè)時(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(); } // 各種類(lèi)型有相同的表現(xiàn)形式,定義一個(gè)統(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ù)不同的類(lèi)型來(lái)繼承 interface FooApi extends BaseApi<Foo> { } interface BarApi extends BaseApi<Bar> { }Logging
你可以通過(guò)設(shè)置一個(gè)?Logger?來(lái)記錄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é)的說(shuō)明
Request Interceptors
當(dāng)你希望修改所有的的請(qǐng)求的時(shí)候,你可以使用Request Interceptors。比如說(shuō),你作為一個(gè)中介,你可能需要為每個(gè)請(qǐng)求設(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");或者,你可能需要實(shí)現(xiàn)Basic Auth,這里有一個(gè)內(nèi)置的基礎(chǔ)校驗(yàn)攔截器?BasicAuthRequestInterceptor
Bank bank = Feign.builder().decoder(accountDecoder).requestInterceptor(new BasicAuthRequestInterceptor(username, password)).target(Bank.class, "https://api.examplebank.com");Custom @Param Expansion
在使用?@Param?注解給模板中的參數(shù)設(shè)值的時(shí)候,默認(rèn)的是使用的對(duì)象的?toString()?方法的值,通過(guò)聲明 自定義的Param.Expander,用戶(hù)可以控制其行為,比如說(shuō)格式化?Date?類(lèi)型的值:
// 通過(guò)設(shè)置 @Param 的 expander 為 DateToMillis.class 可以定義Date類(lèi)型的值 @RequestLine("GET /?since={date}") Result list(@Param(value = "date", expander = DateToMillis.class) Date date);Dynamic Query Parameters
動(dòng)態(tài)查詢(xún)參數(shù)支持,通過(guò)使用?@QueryMap?可以允許動(dòng)態(tài)傳入請(qǐng)求參數(shù),如下:
@RequestLine("GET /find") V find(@QueryMap Map<String, Object> queryMap);Static and Default Methods
如果你使用的是JDK 1.8+ 的話(huà),那么你可以給接口設(shè)置統(tǒng)一的默認(rèn)方法和靜態(tài)方法,這個(gè)事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é)
以上是生活随笔為你收集整理的Feign api调用方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 毫米波雷达数据处理_基于毫米波雷达的桥梁
- 下一篇: python读取excel