做者:六點半起牀
java
juejin.im/post/6854573211426750472git
你們都知道okhttp是一款由square公司開源的java版本http客戶端工具。實際上,square公司還開源了基於okhttp進一步封裝的retrofit工具,用來支持經過接口的方式發起http請求。github
若是你的項目中還在直接使用RestTemplate或者okhttp,或者基於它們封裝的HttpUtils,那麼你能夠嘗試使用Retrofit。web
retrofit-spring-boot-starter
實現了Retrofit與spring-boot框架快速整合,而且支持了部分功能加強,從而極大的簡化spring-boot項目下http接口調用開發。接下來咱們直接經過retrofit-spring-boot-starter
,來看看spring-boot項目發送http請求有多簡單。面試
retrofit官方並無提供與spring-boot快速整合的starter。retrofit-spring-boot-starter
是筆者封裝的,已在生產環境使用,很是穩定。喜歡的話給個star。spring
https://github.com/LianjiaTech/retrofit-spring-boot-starter編程
引入依賴
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
配置@RetrofitScan註解
你能夠給帶有 @Configuration 的類配置@RetrofitScan,或者直接配置到spring-boot的啓動類上,以下:後端
@SpringBootApplication
@RetrofitScan("com.github.lianjiatech.retrofit.spring.boot.test")
public class RetrofitTestApplication {
public static void main(String[] args) {
SpringApplication.run(RetrofitTestApplication.class, args);
}
}
定義http接口
接口必須使用@RetrofitClient註解標記!推薦:一百期面試題彙總api
http相關注解可參考官方文檔:微信
https://square.github.io/retrofit/
@RetrofitClient(baseUrl = "${test.baseUrl}")
public interface HttpApi {
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
}
注入使用
將接口注入到其它Service中便可使用。
@Service
public class TestService {
@Autowired
private HttpApi httpApi;
public void test() {
// 經過httpApi發起http請求
}
}
只要經過上述幾個步驟,就能實現經過接口發送http請求了,真的很簡單。若是你在spring-boot項目裏面使用過mybatis,相信你對這種使用方式會更加熟悉。
接下來咱們繼續介紹一下retrofit-spring-boot-starter
更高級一點的功能。
註解式攔截器
不少時候,咱們但願某個接口下的某些http請求執行統一的攔截處理邏輯。這個時候可使用註解式攔截器。使用的步驟主要分爲2步:
-
繼承BasePathMatchInterceptor編寫攔截處理器; -
接口上使用@Intercept進行標註。
下面以給指定請求的url後面拼接timestamp時間戳爲例,介紹下如何使用註解式攔截器。
繼承BasePathMatchInterceptor編寫攔截處理器
@Component
public class TimeStampInterceptor extends BasePathMatchInterceptor {
@Override
public Response doIntercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl url = request.url();
long timestamp = System.currentTimeMillis();
HttpUrl newUrl = url.newBuilder()
.addQueryParameter("timestamp", String.valueOf(timestamp))
.build();
Request newRequest = request.newBuilder()
.url(newUrl)
.build();
return chain.proceed(newRequest);
}
}
接口上使用@Intercept進行標註
@RetrofitClient(baseUrl = "${test.baseUrl}")
@Intercept(handler = TimeStampInterceptor.class, include = {"/api/**"}, exclude = "/api/test/savePerson")
public interface HttpApi {
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
@POST("savePerson")
Result<Person> savePerson(@Body Person person);
}
上面的@Intercept配置表示:攔截HttpApi接口下/api/**
路徑下(排除/api/test/savePerson)的請求,攔截處理器使用TimeStampInterceptor。推薦:一百期面試題彙總
擴展註解式攔截器
有的時候,咱們須要在攔截註解動態傳入一些參數,而後再執行攔截的時候須要使用這個參數。這種時候,咱們能夠擴展實現自定義攔截註解。
自定義攔截註解必須使用@InterceptMark標記,而且註解中必須包括include()、exclude()、handler()屬性信息。使用的步驟主要分爲3步:
-
自定義攔截註解 -
繼承BasePathMatchInterceptor編寫攔截處理器 -
接口上使用自定義攔截註解;
例如咱們須要在請求頭裏面動態加入accessKeyId、accessKeySecret簽名信息才能正常發起http請求,這個時候能夠自定義一個加簽攔截器註解@Sign來實現。下面以自定義@Sign攔截註解爲例進行說明。
自定義@Sign註解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@InterceptMark
public @interface Sign {
/**
* 密鑰key
* 支持佔位符形式配置。
*
* @return
*/
String accessKeyId();
/**
* 密鑰
* 支持佔位符形式配置。
*
* @return
*/
String accessKeySecret();
/**
* 攔截器匹配路徑
*
* @return
*/
String[] include() default {"/**"};
/**
* 攔截器排除匹配,排除指定路徑攔截
*
* @return
*/
String[] exclude() default {};
/**
* 處理該註解的攔截器類
* 優先從spring容器獲取對應的Bean,若是獲取不到,則使用反射建立一個!
*
* @return
*/
Class<? extends BasePathMatchInterceptor> handler() default SignInterceptor.class;
}
擴展自定義攔截註解有如下2點須要注意:
-
自定義攔截註解必須使用@InterceptMark標記。 -
註解中必須包括include()、exclude()、handler()屬性信息。
實現SignInterceptor
@Component
public class SignInterceptor extends BasePathMatchInterceptor {
private String accessKeyId;
private String accessKeySecret;
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
@Override
public Response doIntercept(Chain chain) throws IOException {
Request request = chain.request();
Request newReq = request.newBuilder()
.addHeader("accessKeyId", accessKeyId)
.addHeader("accessKeySecret", accessKeySecret)
.build();
return chain.proceed(newReq);
}
}
上述accessKeyId和accessKeySecret字段值會依據@Sign註解的accessKeyId()和accessKeySecret()值自動注入,若是@Sign指定的是佔位符形式的字符串,則會取配置屬性值進行注入。
另外,accessKeyId和accessKeySecret字段必須提供setter方法。Java知音公衆號內回覆「後端面試」,送你一份Java面試題寶典
接口上使用@Sign
@RetrofitClient(baseUrl = "${test.baseUrl}")
@Sign(accessKeyId = "${test.accessKeyId}", accessKeySecret = "${test.accessKeySecret}", exclude = {"/api/test/person"})
public interface HttpApi {
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
@POST("savePerson")
Result<Person> savePerson(@Body Person person);
}
這樣就能在指定url的請求上,自動加上簽名信息了。
鏈接池管理
默認狀況下,全部經過Retrofit發送的http請求都會使用max-idle-connections=5 keep-alive-second=300
的默認鏈接池。
固然,咱們也能夠在配置文件中配置多個自定義的鏈接池,而後經過@RetrofitClient的poolName屬性來指定使用。好比咱們要讓某個接口下的請求所有使用poolName=test1的鏈接池,代碼實現以下:
1.配置鏈接池。
retrofit:
# 鏈接池配置
pool:
test1:
max-idle-connections: 3
keep-alive-second: 100
test2:
max-idle-connections: 5
keep-alive-second: 50
2.經過@RetrofitClient的poolName屬性來指定使用的鏈接池。
@RetrofitClient(baseUrl = "${test.baseUrl}", poolName="test1")
public interface HttpApi {
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
}
日誌打印
不少狀況下,咱們但願將http請求日誌記錄下來。經過@RetrofitClient的logLevel和logStrategy屬性,您能夠指定每一個接口的日誌打印級別以及日誌打印策略。
retrofit-spring-boot-starter支持了5種日誌打印級別(ERROR, WARN, INFO, DEBUG, TRACE),默認INFO;支持了4種日誌打印策略(NONE, BASIC, HEADERS, BODY),默認BASIC。
4種日誌打印策略含義以下:
-
NONE:No logs. -
BASIC:Logs request and response lines. -
HEADERS:Logs request and response lines and their respective headers. -
BODY:Logs request and response lines and their respective headers and bodies (if present).
retrofit-spring-boot-starter默認使用了DefaultLoggingInterceptor執行真正的日誌打印功能,其底層就是okhttp原生的HttpLoggingInterceptor。
固然,你也能夠自定義實現本身的日誌打印攔截器,只須要繼承BaseLoggingInterceptor(具體能夠參考DefaultLoggingInterceptor的實現),而後在配置文件中進行相關配置便可。
retrofit:
# 日誌打印攔截器
logging-interceptor: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor
Http異常信息格式化器
當出現http請求異常時,原始的異常信息可能閱讀起來並不友好,所以retrofit-spring-boot-starter提供了Http異常信息格式化器,用來美化輸出http請求參數,默認使用DefaultHttpExceptionMessageFormatter進行請求數據格式化。Java知音公衆號內回覆「後端面試」,送你一份Java面試題寶典
你也能夠進行自定義,只須要繼承BaseHttpExceptionMessageFormatter,再進行相關配置便可。
retrofit:
# Http異常信息格式化器
http-exception-message-formatter: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultHttpExceptionMessageFormatter
調用適配器 CallAdapter
Retrofit能夠經過調用適配器CallAdapterFactory將Call<T>
對象適配成接口方法的返回值類型。retrofit-spring-boot-starter擴展2種CallAdapterFactory實現:
BodyCallAdapterFactory
-
默認啓用,可經過配置retrofit.enable-body-call-adapter=false關閉 -
同步執行http請求,將響應體內容適配成接口方法的返回值類型實例。 -
除了 Retrofit.Call<T>
、Retrofit.Response<T>
、java.util.concurrent.CompletableFuture<T>
以外,其它返回類型均可以使用該適配器。
ResponseCallAdapterFactory
-
默認啓用,可經過配置 retrofit.enable-response-call-adapter=false
關閉 -
同步執行http請求,將響應體內容適配成 Retrofit.Response<T>
返回。 -
若是方法的返回值類型爲 Retrofit.Response<T>
,則可使用該適配器。
Retrofit自動根據方法返回值類型選用對應的CallAdapterFactory執行適配處理!加上Retrofit默認的CallAdapterFactory,可支持多種形式的方法返回值類型:
-
Call<T>
: 不執行適配處理,直接返回Call<T>
對象 -
CompletableFuture<T>
: 將響應體內容適配成CompletableFuture<T>
對象返回 -
Void: 不關注返回類型可使用Void。若是http狀態碼不是2xx,直接拋錯! -
Response<T>
: 將響應內容適配成Response<T>
對象返回 -
其餘任意Java類型:將響應體內容適配成一個對應的Java類型對象返回,若是http狀態碼不是2xx,直接拋錯!
/**
* Call<T>
* 不執行適配處理,直接返回Call<T>對象
* @param id
* @return
*/
@GET("person")
Call<Result<Person>> getPersonCall(@Query("id") Long id);
/**
* CompletableFuture<T>
* 將響應體內容適配成CompletableFuture<T>對象返回
* @param id
* @return
*/
@GET("person")
CompletableFuture<Result<Person>> getPersonCompletableFuture(@Query("id") Long id);
/**
* Void
* 不關注返回類型可使用Void。若是http狀態碼不是2xx,直接拋錯!
* @param id
* @return
*/
@GET("person")
Void getPersonVoid(@Query("id") Long id);
/**
* Response<T>
* 將響應內容適配成Response<T>對象返回
* @param id
* @return
*/
@GET("person")
Response<Result<Person>> getPersonResponse(@Query("id") Long id);
/**
* 其餘任意Java類型
* 將響應體內容適配成一個對應的Java類型對象返回,若是http狀態碼不是2xx,直接拋錯!
* @param id
* @return
*/
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
咱們也能夠經過繼承CallAdapter.Factory擴展實現本身的CallAdapter;而後將自定義的CallAdapterFactory配置成spring的bean!
自定義配置的CallAdapter.Factory優先級更高!
數據轉碼器 Converter
Retrofi使用Converter將@Body註解標註的對象轉換成請求體,將響應體數據轉換成一個Java對象,能夠選用如下幾種Converter:
-
Gson: com.squareup.Retrofit:converter-gson -
Jackson: com.squareup.Retrofit:converter-jackson -
Moshi: com.squareup.Retrofit:converter-moshi -
Protobuf: com.squareup.Retrofit:converter-protobuf -
Wire: com.squareup.Retrofit:converter-wire -
Simple XML: com.squareup.Retrofit:converter-simplexml
retrofit-spring-boot-starter默認使用的是jackson進行序列化轉換!若是須要使用其它序列化方式,在項目中引入對應的依賴,再把對應的ConverterFactory配置成spring的bean便可。
咱們也能夠經過繼承Converter.Factory擴展實現本身的Converter;而後將自定義的Converter.Factory配置成spring的bean!
自定義配置的Converter.Factory優先級更高!
全局攔截器 BaseGlobalInterceptor
若是咱們須要對整個系統的的http請求執行統一的攔截處理,能夠自定義實現全局攔截器BaseGlobalInterceptor, 並配置成spring中的bean!例如咱們須要在整個系統發起的http請求,都帶上來源信息。
@Component
public class SourceInterceptor extends BaseGlobalInterceptor {
@Override
public Response doIntercept(Chain chain) throws IOException {
Request request = chain.request();
Request newReq = request.newBuilder()
.addHeader("source", "test")
.build();
return chain.proceed(newReq);
}
}
結語
至此,spring-boot項目下最優雅的http客戶端工具介紹就結束了,更多詳細信息能夠參考官方文檔:retrofit以及retrofit-spring-boot-starter。
https://github.com/LianjiaTech/retrofit-spring-boot-starter
![]()
最後免費給你們分享50個Java項目實戰資料,涵蓋入門、進階各個階段學習內容,能夠說很是全面了。大部分視頻還附帶源碼,學起來還不費勁!
附上截圖。(下面有下載方式)。
項目領取方式:
掃描下方公衆號回覆:50,
可獲取下載連接
👇👇👇
👆 長按上方二維碼 2 秒 回覆「 50 」便可獲取資料
點贊是最大的支持
本文分享自微信公衆號 - 武哥聊編程(eson_15)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。