<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          SpringBoot項目整合最優(yōu)雅的HTTP客戶端工具 - Retrofit

          共 15783字,需瀏覽 32分鐘

           ·

          2021-09-11 23:18

          點擊上方 Java學習之道,選擇 設為星標

          每天18:30點,干貨準時奉上!

          作者: 陳添明
          參考: https://juejin.cn/post/6854573211426750472

          Part1SpringBoot項目整合最優(yōu)雅的HTTP客戶端工具 - Retrofit最佳實踐

          大家都知道 okhttp 是一款由 square 公司開源的java版本http客戶端工具。實際上,square 公司還開源了基于okhttp進一步封裝的 retrofit 工具,用來支持通過接口的方式發(fā)起http請求。

          如果你的項目中還在直接使用RestTemplate或者okhttp,或者基于它們封裝的HttpUtils,那么你可以嘗試使用Retrofit。

          retrofit-spring-boot-starter實現(xiàn)了Retrofitspring-boot框架快速整合,并且支持了部分功能增強,從而極大的簡化spring-boot項目下http接口調(diào)用開發(fā)。接下來我們直接通過retrofit-spring-boot-starter,來看看spring-boot項目發(fā)送http請求有多簡單。

          retrofit官方并沒有提供與spring-boot快速整合的starter。retrofit-spring-boot-starter是筆者封裝的,已在生產(chǎn)環(huán)境使用,非常穩(wěn)定。造輪子不易,跪求各位大佬star。

          retrofit-spring-boot-starter 項目源碼地址:

          https://github.com/LianjiaTech/retrofit-spring-boot-starter

          Part2實際操作

          1引入依賴

          <dependency>
              <groupId>com.github.lianjiatech</groupId>
              <artifactId>retrofit-spring-boot-starter</artifactId>
              <version>2.0.2</version>
          </dependency>

          2配置@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.classargs);
              }
          }

          3定義http接口

          接口必須使用@RetrofitClient注解標記!

          http相關注解可參考官方文檔:retrofit官方文檔 https://square.github.io/retrofit/。

          @RetrofitClient(baseUrl = "${test.baseUrl}")
          public interface HttpApi {

              @GET("person")
              Result<Person> getPerson(@Query("id") Long id);
          }

          4注入使用

          將接口注入到其它Service中即可使用。

          @Service
          public class TestService {

              @Autowired
              private HttpApi httpApi;

              public void test() {
                  // 通過httpApi發(fā)起http請求
              }
          }

          只要通過上述幾個步驟,就能實現(xiàn)通過接口發(fā)送http請求了,真的很簡單。如果你在spring-boot項目里面使用過mybatis,相信你對這種使用方式會更加熟悉。接下來我們繼續(xù)介紹一下retrofit-spring-boot-starter更高級一點的功能。

          5注解式攔截器

          很多時候,我們希望某個接口下的某些http請求執(zhí)行統(tǒng)一的攔截處理邏輯。這個時候可以使用注解式攔截器。使用的步驟主要分為2步:

          1. 繼承BasePathMatchInterceptor編寫攔截處理器;
          2. 接口上使用@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.classinclude = {"/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。

          6擴展注解式攔截器

          有的時候,我們需要在攔截注解動態(tài)傳入一些參數(shù),然后再執(zhí)行攔截的時候需要使用這個參數(shù)。這種時候,我們可以擴展實現(xiàn)自定義攔截注解。自定義攔截注解必須使用@InterceptMark標記,并且注解中必須包括include()、exclude()、handler()屬性信息。使用的步驟主要分為3步:

          1. 自定義攔截注解
          2. 繼承BasePathMatchInterceptor編寫攔截處理器
          3. 接口上使用自定義攔截注解;

          例如我們需要在請求頭里面動態(tài)加入accessKeyId、accessKeySecret簽名信息才能正常發(fā)起http請求,這個時候可以**自定義一個加簽攔截器注解@Sign**來實現(xiàn)。下面以自定義@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 {};

              /**
               * 處理該注解的攔截器類
               * 優(yōu)先從spring容器獲取對應的Bean,如果獲取不到,則使用反射創(chuàng)建一個!
               *
               * @return
               */

              Class<? extends BasePathMatchInterceptor> handler() default SignInterceptor.class;
          }

          擴展自定義攔截注解有以下2點需要注意:

          1. 自定義攔截注解必須使用@InterceptMark標記。
          2. 注解中必須包括include()、exclude()、handler()屬性信息。

          實現(xiàn)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);
              }
          }

          上述accessKeyIdaccessKeySecret字段值會依據(jù)@Sign注解的accessKeyId()accessKeySecret()值自動注入,如果@Sign指定的是占位符形式的字符串,則會取配置屬性值進行注入。另外,accessKeyIdaccessKeySecret字段必須提供setter方法。

          接口上使用@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的請求上,自動加上簽名信息了。

          7連接池管理

          默認情況下,所有通過Retrofit發(fā)送的http請求都會使用max-idle-connections=5 keep-alive-second=300的默認連接池。當然,我們也可以在配置文件中配置多個自定義的連接池,然后通過@RetrofitClientpoolName屬性來指定使用。比如我們要讓某個接口下的請求全部使用poolName=test1的連接池,代碼實現(xiàn)如下:

          1. 配置連接池。
          retrofit:
             # 連接池配置
             pool:
                 test1:
                 max-idle-connections: 3
                 keep-alive-second: 100
                 test2:
                 max-idle-connections: 5
                 keep-alive-second: 50
          1. 通過@RetrofitClientpoolName屬性來指定使用的連接池。
          @RetrofitClient(baseUrl = "${test.baseUrl}", poolName="test1")
          public interface HttpApi {

             @GET("person")
             Result<Person> getPerson(@Query("id") Long id);
          }

          8日志打印

          很多情況下,我們希望將http請求日志記錄下來。通過@RetrofitClientlogLevellogStrategy屬性,您可以指定每個接口的日志打印級別以及日志打印策略。retrofit-spring-boot-starter支持了5種日志打印級別(ERROR, WARN, INFO, DEBUG, TRACE),默認INFO;支持了4種日志打印策略(NONE, BASIC, HEADERS, BODY),默認BASIC。4種日志打印策略含義如下:

          1. NONE:No logs.
          2. BASIC:Logs request and response lines.
          3. HEADERS:Logs request and response lines and their respective headers.
          4. BODY:Logs request and response lines and their respective headers and bodies (if present).

          retrofit-spring-boot-starter默認使用了DefaultLoggingInterceptor執(zhí)行真正的日志打印功能,其底層就是okhttp原生的HttpLoggingInterceptor。當然,你也可以自定義實現(xiàn)自己的日志打印攔截器,只需要繼承BaseLoggingInterceptor(具體可以參考DefaultLoggingInterceptor的實現(xiàn)),然后在配置文件中進行相關配置即可。

          retrofit:
            # 日志打印攔截器
            logging-interceptor: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor

          9Http異常信息格式化器

          當出現(xiàn)http請求異常時,原始的異常信息可能閱讀起來并不友好,因此retrofit-spring-boot-starter提供了Http異常信息格式化器,用來美化輸出http請求參數(shù),默認使用DefaultHttpExceptionMessageFormatter進行請求數(shù)據(jù)格式化。你也可以進行自定義,只需要繼承BaseHttpExceptionMessageFormatter,再進行相關配置即可。

          retrofit:
            # Http異常信息格式化器
            http-exception-message-formatter: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultHttpExceptionMessageFormatter

          10調(diào)用適配器 CallAdapter

          Retrofit可以通過調(diào)用適配器CallAdapterFactoryCall<T>對象適配成接口方法的返回值類型。retrofit-spring-boot-starter擴展2種CallAdapterFactory實現(xiàn):

          1. BodyCallAdapterFactory
            • 默認啟用,可通過配置retrofit.enable-body-call-adapter=false關閉
            • 同步執(zhí)行http請求,將響應體內(nèi)容適配成接口方法的返回值類型實例。
            • 除了Retrofit.Call<T>、Retrofit.Response<T>、java.util.concurrent.CompletableFuture<T>之外,其它返回類型都可以使用該適配器。
          2. ResponseCallAdapterFactory
            • 默認啟用,可通過配置retrofit.enable-response-call-adapter=false關閉
            • 同步執(zhí)行http請求,將響應體內(nèi)容適配成Retrofit.Response<T>返回。
            • 如果方法的返回值類型為Retrofit.Response<T>,則可以使用該適配器。

          Retrofit自動根據(jù)方法返回值類型選用對應的CallAdapterFactory執(zhí)行適配處理!加上Retrofit默認的CallAdapterFactory,可支持多種形式的方法返回值類型:

          • Call<T>: 不執(zhí)行適配處理,直接返回Call<T>對象
          • CompletableFuture<T>: 將響應體內(nèi)容適配成CompletableFuture<T>對象返回
          • Void: 不關注返回類型可以使用Void。如果http狀態(tài)碼不是2xx,直接拋錯!
          • Response<T>: 將響應內(nèi)容適配成Response<T>對象返回
          • 其他任意Java類型:將響應體內(nèi)容適配成一個對應的Java類型對象返回,如果http狀態(tài)碼不是2xx,直接拋錯!
              /**
               * Call<T>
               * 不執(zhí)行適配處理,直接返回Call<T>對象
               * @param id
               * @return
               */

              @GET("person")
              Call<Result<Person>> getPersonCall(@Query("id") Long id);

              /**
               *  CompletableFuture<T>
               *  將響應體內(nèi)容適配成CompletableFuture<T>對象返回
               * @param id
               * @return
               */

              @GET("person")
              CompletableFuture<Result<Person>> getPersonCompletableFuture(@Query("id") Long id);

              /**
               * Void
               * 不關注返回類型可以使用Void。如果http狀態(tài)碼不是2xx,直接拋錯!
               * @param id
               * @return
               */

              @GET("person")
              Void getPersonVoid(@Query("id") Long id);

              /**
               *  Response<T>
               *  將響應內(nèi)容適配成Response<T>對象返回
               * @param id
               * @return
               */

              @GET("person")
              Response<Result<Person>> getPersonResponse(@Query("id") Long id);

              /**
               * 其他任意Java類型
               * 將響應體內(nèi)容適配成一個對應的Java類型對象返回,如果http狀態(tài)碼不是2xx,直接拋錯!
               * @param id
               * @return
               */

              @GET("person")
              Result<Person> getPerson(@Query("id") Long id);

          我們也可以通過繼承CallAdapter.Factory擴展實現(xiàn)自己的CallAdapter;然后將自定義的CallAdapterFactory配置成springbean!

          自定義配置的CallAdapter.Factory優(yōu)先級更高!

          11數(shù)據(jù)轉碼器 Converter

          Retrofi使用Converter@Body注解標注的對象轉換成請求體,將響應體數(shù)據(jù)轉換成一個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擴展實現(xiàn)自己的Converter;然后將自定義的Converter.Factory配置成springbean!

          自定義配置的Converter.Factory優(yōu)先級更高!

          12全局攔截器 BaseGlobalInterceptor

          如果我們需要對整個系統(tǒng)的的http請求執(zhí)行統(tǒng)一的攔截處理,可以自定義實現(xiàn)全局攔截器BaseGlobalInterceptor, 并配置成spring中的bean!例如我們需要在整個系統(tǒng)發(fā)起的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);
              }
          }

          Part3結語

          至此,spring-boot項目下最優(yōu)雅的http客戶端工具介紹就結束了,更多詳細信息可以參考官方文檔:retrofit 以及 retrofit-spring-boot-starter :

          https://github.com/LianjiaTech/retrofit-spring-boot-starter

           | 更多精彩文章 -



          加我微信,交個朋友
          長按/掃碼添加↑↑↑

          瀏覽 44
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  成人网站十八禁 | 日韩激情综合网 | 操逼操123| 性爱小说视频 | 北条麻美在线无码 |