<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>

          推薦一款適用于 Spring Boot 的神級(jí) HTTP 客戶端框架,賊好用。。

          共 29522字,需瀏覽 60分鐘

           ·

          2021-08-29 08:13

          SpringBoot項(xiàng)目直接使用okhttphttpClient或者RestTemplate發(fā)起HTTP請(qǐng)求,既繁瑣又不方便統(tǒng)一管理。

          因此,在這里推薦一個(gè)適用于SpringBoot項(xiàng)目的輕量級(jí)HTTP客戶端框架retrofit-spring-boot-starter,使用非常簡單方便,同時(shí)又提供諸多功能增強(qiáng)。目前項(xiàng)目已經(jīng)更新至2.2.2版本,并且會(huì)持續(xù)進(jìn)行迭代優(yōu)化。

          前言

          Retrofit是適用于AndroidJava且類型安全的HTTP客戶端,其最大的特性的是支持通過接口的方式發(fā)起HTTP請(qǐng)求 。而spring-boot是使用最廣泛的Java開發(fā)框架,但是Retrofit官方?jīng)]有支持與spring-boot框架快速整合,因此我們開發(fā)了retrofit-spring-boot-starter

          retrofit-spring-boot-starter實(shí)現(xiàn)了Retrofitspring-boot框架快速整合,并且支持了諸多功能增強(qiáng),極大簡化開發(fā)

          ??項(xiàng)目持續(xù)優(yōu)化迭代。

          功能特性

          • 自定義注入OkHttpClient
          • 注解式攔截器
          • 連接池管理
          • 日志打印
          • 請(qǐng)求重試
          • 錯(cuò)誤解碼器
          • 全局?jǐn)r截器
          • 熔斷降級(jí)
          • 微服務(wù)之間的HTTP調(diào)用
          • 調(diào)用適配器
          • 數(shù)據(jù)轉(zhuǎn)換器

          快速使用

          引入依賴

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

          定義http接口

          接口必須使用@RetrofitClient注解標(biāo)記 !http相關(guān)注解可參考官方文檔:retrofit官方文檔。Spring Boot 學(xué)習(xí)筆記,學(xué)習(xí)下吧。

          @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發(fā)起http請(qǐng)求
              }
          }

          HTTP請(qǐng)求相關(guān)注解

          HTTP請(qǐng)求相關(guān)注解,全部使用了retrofit原生注解。詳細(xì)信息可參考官方文檔:retrofit官方文檔 ,以下是一個(gè)簡單說明。

          注解分類支持的注解
          請(qǐng)求方式@GET @HEAD @POST @PUT @DELETE @OPTIONS
          請(qǐng)求頭@Header @HeaderMap @Headers
          Query參數(shù)@Query @QueryMap @QueryName
          path參數(shù)@Path
          form-encoded參數(shù)@Field @FieldMap @FormUrlEncoded
          文件上傳@Multipart @Part @PartMap
          url參數(shù)@Url

          配置項(xiàng)說明

          retrofit-spring-boot-starter支持了多個(gè)可配置的屬性,用來應(yīng)對(duì)不同的業(yè)務(wù)場景。您可以視情況進(jìn)行修改,具體說明如下:

          配置默認(rèn)值說明
          enable-logtrue啟用日志打印
          logging-interceptorDefaultLoggingInterceptor日志打印攔截器
          pool
          連接池配置
          disable-void-return-typefalse禁用java.lang.Void返回類型
          retry-interceptorDefaultRetryInterceptor請(qǐng)求重試攔截器
          global-converter-factoriesJacksonConverterFactory全局轉(zhuǎn)換器工廠
          global-call-adapter-factoriesBodyCallAdapterFactory,ResponseCallAdapterFactory全局調(diào)用適配器工廠
          enable-degradefalse是否啟用熔斷降級(jí)
          degrade-typesentinel熔斷降級(jí)實(shí)現(xiàn)方式(目前僅支持Sentinel)
          resource-name-parserDefaultResourceNameParser熔斷資源名稱解析器,用于解析資源名稱

          yml配置方式:

          retrofit:
            enable-response-call-adapter: true
            # 啟用日志打印
            enable-log: true
            # 連接池配置
            pool:
              test1:
                max-idle-connections: 3
                keep-alive-second: 100
              test2:
                max-idle-connections: 5
                keep-alive-second: 50
            # 禁用void返回值類型
            disable-void-return-type: false
            # 日志打印攔截器
            logging-interceptor: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor
            # 請(qǐng)求重試攔截器
            retry-interceptor: com.github.lianjiatech.retrofit.spring.boot.retry.DefaultRetryInterceptor
            # 全局轉(zhuǎn)換器工廠
            global-converter-factories:
              - retrofit2.converter.jackson.JacksonConverterFactory
            # 全局調(diào)用適配器工廠
            global-call-adapter-factories:
              - com.github.lianjiatech.retrofit.spring.boot.core.BodyCallAdapterFactory
              - com.github.lianjiatech.retrofit.spring.boot.core.ResponseCallAdapterFactory
            # 是否啟用熔斷降級(jí)
            enable-degrade: true
            # 熔斷降級(jí)實(shí)現(xiàn)方式
            degrade-type: sentinel
            # 熔斷資源名稱解析器
            resource-name-parser: com.github.lianjiatech.retrofit.spring.boot.degrade.DefaultResourceNameParser

          高級(jí)功能

          自定義注入OkHttpClient

          通常情況下,通過@RetrofitClient注解屬性動(dòng)態(tài)創(chuàng)建OkHttpClient對(duì)象能夠滿足大部分使用場景。但是在某些情況下,用戶可能需要自定義OkHttpClient,這個(gè)時(shí)候,可以在接口上定義返回類型是OkHttpClient.Builder的靜態(tài)方法來實(shí)現(xiàn)。代碼示例如下:

          @RetrofitClient(baseUrl = "http://ke.com")
          public interface HttpApi3 {

              @OkHttpClientBuilder
              static OkHttpClient.Builder okhttpClientBuilder() {
                  return new OkHttpClient.Builder()
                          .connectTimeout(1, TimeUnit.SECONDS)
                          .readTimeout(1, TimeUnit.SECONDS)
                          .writeTimeout(1, TimeUnit.SECONDS);

              }

              @GET
              Result<Person> getPerson(@Url String url, @Query("id") Long id);
          }

          方法必須使用@OkHttpClientBuilder注解標(biāo)記!

          注解式攔截器

          很多時(shí)候,我們希望某個(gè)接口下的某些http請(qǐng)求執(zhí)行統(tǒng)一的攔截處理邏輯。為了支持這個(gè)功能,retrofit-spring-boot-starter提供了注解式攔截器 ,做到了基于url路徑的匹配攔截 。使用的步驟主要分為2步:

          1. 繼承BasePathMatchInterceptor編寫攔截處理器;
          2. 接口上使用@Intercept進(jìn)行標(biāo)注。如需配置多個(gè)攔截器,在接口上標(biāo)注多個(gè)@Intercept注解即可!

          下面以給指定請(qǐng)求的url后面拼接timestamp時(shí)間戳為例,介紹下如何使用注解式攔截器。Spring Boot 學(xué)習(xí)筆記,分享學(xué)習(xí)下。

          繼承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進(jìn)行標(biāo)注
          @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)的請(qǐng)求,攔截處理器使用TimeStampInterceptor

          擴(kuò)展注解式攔截器

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

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

          例如我們需要在請(qǐng)求頭里面動(dòng)態(tài)加入accessKeyIdaccessKeySecret簽名信息才能正常發(fā)起http請(qǐng)求 ,這個(gè)時(shí)候可以自定義一個(gè)加簽攔截器注解@Sign來實(shí)現(xiàn) 。下面以自定義@Sign攔截注解為例進(jìn)行說明。

          自定義@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容器獲取對(duì)應(yīng)的Bean,如果獲取不到,則使用反射創(chuàng)建一個(gè)!
               *
               * @return
               */

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

          擴(kuò)展自定義攔截注解有以下2點(diǎn)需要注意:

          1. 自定義攔截注解必須使用@InterceptMark標(biāo)記。
          2. 注解中必須包括include()、exclude()、handler()屬性信息。
          實(shí)現(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字段值會(huì)依據(jù)@Sign注解的accessKeyId()accessKeySecret()值自動(dòng)注入,如果@Sign指定的是占位符形式的字符串,則會(huì)取配置屬性值進(jìn)行注入 。另外,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的請(qǐng)求上,自動(dòng)加上簽名信息了。

          連接池管理

          默認(rèn)情況下,所有通過Retrofit發(fā)送的http請(qǐng)求都會(huì)使用max-idle-connections=5 keep-alive-second=300的默認(rèn)連接池。當(dāng)然,我們也可以在配置文件中配置多個(gè)自定義的連接池,然后通過@RetrofitClientpoolName屬性來指定使用。比如我們要讓某個(gè)接口下的請(qǐng)求全部使用poolName=test1的連接池,代碼實(shí)現(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);
             }

          日志打印

          很多情況下,我們希望將http請(qǐng)求日志記錄下來。通過retrofit.enableLog配置可以全局控制日志是否開啟。針對(duì)每個(gè)接口,可以通過@RetrofitClientenableLog控制是否開啟,通過logLevellogStrategy,可以指定每個(gè)接口的日志打印級(jí)別以及日志打印策略。retrofit-spring-boot-starter支持了5種日志打印級(jí)別(ERROR, WARN, INFO, DEBUG, TRACE),默認(rèn)INFO;支持了4種日志打印策略(NONE, BASIC, HEADERS, BODY),默認(rèn)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默認(rèn)使用了DefaultLoggingInterceptor執(zhí)行真正的日志打印功能,其底層就是okhttp原生的HttpLoggingInterceptor。當(dāng)然,你也可以自定義實(shí)現(xiàn)自己的日志打印攔截器,只需要繼承BaseLoggingInterceptor(具體可以參考DefaultLoggingInterceptor的實(shí)現(xiàn)),然后在配置文件中進(jìn)行相關(guān)配置即可。

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

          請(qǐng)求重試

          retrofit-spring-boot-starter支持請(qǐng)求重試功能,只需要在接口或者方法上加上@Retry注解即可。@Retry支持重試次數(shù)maxRetries、重試時(shí)間間隔intervalMs以及重試規(guī)則retryRules配置

          重試規(guī)則支持三種配置:

          1. RESPONSE_STATUS_NOT_2XX:響應(yīng)狀態(tài)碼不是2xx時(shí)執(zhí)行重試;
          2. OCCUR_IO_EXCEPTION:發(fā)生IO異常時(shí)執(zhí)行重試;
          3. OCCUR_EXCEPTION:發(fā)生任意異常時(shí)執(zhí)行重試;

          默認(rèn)響應(yīng)狀態(tài)碼不是2xx或者發(fā)生IO異常時(shí)自動(dòng)進(jìn)行重試。需要的話,你也可以繼承BaseRetryInterceptor實(shí)現(xiàn)自己的請(qǐng)求重試攔截器,然后將其配置上去。

          retrofit:
            # 請(qǐng)求重試攔截器
            retry-interceptor: com.github.lianjiatech.retrofit.spring.boot.retry.DefaultRetryInterceptor

          關(guān)注公眾號(hào),學(xué)習(xí)更多 Java 干貨!

          錯(cuò)誤解碼器

          HTTP發(fā)生請(qǐng)求錯(cuò)誤(包括發(fā)生異常或者響應(yīng)數(shù)據(jù)不符合預(yù)期)的時(shí)候,錯(cuò)誤解碼器可將HTTP相關(guān)信息解碼到自定義異常中。你可以在@RetrofitClient注解的errorDecoder()指定當(dāng)前接口的錯(cuò)誤解碼器,自定義錯(cuò)誤解碼器需要實(shí)現(xiàn)ErrorDecoder接口:

          /**
           * 錯(cuò)誤解碼器。ErrorDecoder.
           * 當(dāng)請(qǐng)求發(fā)生異常或者收到無效響應(yīng)結(jié)果的時(shí)候,將HTTP相關(guān)信息解碼到異常中,無效響應(yīng)由業(yè)務(wù)自己判斷
           *
           * When an exception occurs in the request or an invalid response result is received, the HTTP related information is decoded into the exception,
           * and the invalid response is determined by the business itself.
           *
           * @author 陳添明
           */

          public interface ErrorDecoder {

              /**
               * 當(dāng)無效響應(yīng)的時(shí)候,將HTTP信息解碼到異常中,無效響應(yīng)由業(yè)務(wù)自行判斷。
               * When the response is invalid, decode the HTTP information into the exception, invalid response is determined by business.
               *
               * @param request  request
               * @param response response
               * @return If it returns null, the processing is ignored and the processing continues with the original response.
               */

              default RuntimeException invalidRespDecode(Request request, Response response) {
                  if (!response.isSuccessful()) {
                      throw RetrofitException.errorStatus(request, response);
                  }
                  return null;
              }


              /**
               * 當(dāng)請(qǐng)求發(fā)生IO異常時(shí),將HTTP信息解碼到異常中。
               * When an IO exception occurs in the request, the HTTP information is decoded into the exception.
               *
               * @param request request
               * @param cause   IOException
               * @return RuntimeException
               */

              default RuntimeException ioExceptionDecode(Request request, IOException cause) {
                  return RetrofitException.errorExecuting(request, cause);
              }

              /**
               * 當(dāng)請(qǐng)求發(fā)生除IO異常之外的其它異常時(shí),將HTTP信息解碼到異常中。
               * When the request has an exception other than the IO exception, the HTTP information is decoded into the exception.
               *
               * @param request request
               * @param cause   Exception
               * @return RuntimeException
               */

              default RuntimeException exceptionDecode(Request request, Exception cause) {
                  return RetrofitException.errorUnknown(request, cause);
              }

          }

          全局?jǐn)r截器

          全局應(yīng)用攔截器

          如果我們需要對(duì)整個(gè)系統(tǒng)的的http請(qǐng)求執(zhí)行統(tǒng)一的攔截處理,可以自定義實(shí)現(xiàn)全局?jǐn)r截器BaseGlobalInterceptor, 并配置成spring容器中的bean!例如我們需要在整個(gè)系統(tǒng)發(fā)起的http請(qǐng)求,都帶上來源信息。

          @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);
              }
          }

          全局網(wǎng)絡(luò)攔截器

          只需要實(shí)現(xiàn)NetworkInterceptor接口 并配置成spring容器中的bean就支持自動(dòng)織入全局網(wǎng)絡(luò)攔截器。

          熔斷降級(jí)

          在分布式服務(wù)架構(gòu)中,對(duì)不穩(wěn)定的外部服務(wù)進(jìn)行熔斷降級(jí)是保證服務(wù)高可用的重要措施之一。由于外部服務(wù)的穩(wěn)定性是不能保證的,當(dāng)外部服務(wù)不穩(wěn)定時(shí),響應(yīng)時(shí)間會(huì)變長。相應(yīng)地,調(diào)用方的響應(yīng)時(shí)間也會(huì)變長,線程會(huì)產(chǎn)生堆積,最終可能耗盡調(diào)用方的線程池,導(dǎo)致整個(gè)服務(wù)不可用。因此我們需要對(duì)不穩(wěn)定的弱依賴服務(wù)調(diào)用進(jìn)行熔斷降級(jí),暫時(shí)切斷不穩(wěn)定調(diào)用,避免局部不穩(wěn)定導(dǎo)致整體服務(wù)雪崩。

          retrofit-spring-boot-starter支持熔斷降級(jí)功能,底層基于Sentinel實(shí)現(xiàn)。具體來說,支持了熔斷資源自發(fā)現(xiàn)注解式降級(jí)規(guī)則配置 。如需使用熔斷降級(jí),只需要進(jìn)行以下操作即可:

          1. 開啟熔斷降級(jí)功能

          默認(rèn)情況下,熔斷降級(jí)功能是關(guān)閉的,需要設(shè)置相應(yīng)的配置項(xiàng)來開啟熔斷降級(jí)功能

          retrofit:
            # 是否啟用熔斷降級(jí)
            enable-degrade: true
            # 熔斷降級(jí)實(shí)現(xiàn)方式(目前僅支持Sentinel)
            degrade-type: sentinel
            # 資源名稱解析器
            resource-name-parser: com.github.lianjiatech.retrofit.spring.boot.degrade.DefaultResourceNameParser

          資源名稱解析器用于實(shí)現(xiàn)用戶自定義資源名稱,默認(rèn)配置是DefaultResourceNameParser,對(duì)應(yīng)的資源名稱格式為HTTP_OUT:GET:http://localhost:8080/api/degrade/test。用戶可以繼承BaseResourceNameParser類實(shí)現(xiàn)自己的資源名稱解析器。

          另外,由于熔斷降級(jí)功能是可選的,因此啟用熔斷降級(jí)需要用戶自行引入Sentinel依賴

          <dependency>
              <groupId>com.alibaba.csp</groupId>
              <artifactId>sentinel-core</artifactId>
              <version>1.6.3</version>
          </dependency>
          2. 配置降級(jí)規(guī)則(可選)

          retrofit-spring-boot-starter支持注解式配置降級(jí)規(guī)則,通過@Degrade注解來配置降級(jí)規(guī)則@Degrade注解可以配置在接口或者方法上,配置在方法上的優(yōu)先級(jí)更高。

          @Retention(RetentionPolicy.RUNTIME)
          @Target({ElementType.METHOD, ElementType.TYPE})
          @Documented
          public @interface Degrade {

              /**
               * RT threshold or exception ratio threshold count.
               */

              double count();

              /**
               * Degrade recover timeout (in seconds) when degradation occurs.
               */

              int timeWindow() default 5;

              /**
               * Degrade strategy (0: average RT, 1: exception ratio).
               */

              DegradeStrategy degradeStrategy() default DegradeStrategy.AVERAGE_RT;
          }

          如果應(yīng)用項(xiàng)目已支持通過配置中心配置降級(jí)規(guī)則,可忽略注解式配置方式

          3. @RetrofitClient設(shè)置fallback或者fallbackFactory (可選)

          如果@RetrofitClient不設(shè)置fallback或者fallbackFactory,當(dāng)觸發(fā)熔斷時(shí),會(huì)直接拋出RetrofitBlockException異常。用戶可以通過設(shè)置fallback或者fallbackFactory來定制熔斷時(shí)的方法返回值fallback類必須是當(dāng)前接口的實(shí)現(xiàn)類,fallbackFactory必須是FallbackFactory<T>實(shí)現(xiàn)類,泛型參數(shù)類型為當(dāng)前接口類型。另外,fallbackfallbackFactory實(shí)例必須配置成Spring容器的Bean

          fallbackFactory相對(duì)于fallback,主要差別在于能夠感知每次熔斷的異常原因(cause) 。參考示例如下:

          @Slf4j
          @Service
          public class HttpDegradeFallback implements HttpDegradeApi {

              @Override
              public Result<Integer> test() {
                  Result<Integer> fallback = new Result<>();
                  fallback.setCode(100)
                          .setMsg("fallback")
                          .setBody(1000000);
                  return fallback;
              }
          }
          @Slf4j
          @Service
          public class HttpDegradeFallbackFactory implements FallbackFactory<HttpDegradeApi{

              /**
               * Returns an instance of the fallback appropriate for the given cause
               *
               * @param cause fallback cause
               * @return 實(shí)現(xiàn)了retrofit接口的實(shí)例。an instance that implements the retrofit interface.
               */

              @Override
              public HttpDegradeApi create(Throwable cause) {
                  log.error("觸發(fā)熔斷了! ", cause.getMessage(), cause);
                  return new HttpDegradeApi() {
                      @Override
                      public Result<Integer> test() {
                          Result<Integer> fallback = new Result<>();
                          fallback.setCode(100)
                                  .setMsg("fallback")
                                  .setBody(1000000);
                          return fallback;
                      }
              }
          }

          微服務(wù)之間的HTTP調(diào)用

          為了能夠使用微服務(wù)調(diào)用,需要進(jìn)行如下配置:

          配置ServiceInstanceChooserSpring容器Bean

          用戶可以自行實(shí)現(xiàn)ServiceInstanceChooser接口,完成服務(wù)實(shí)例的選取邏輯,并將其配置成Spring容器的Bean。對(duì)于Spring Cloud應(yīng)用,retrofit-spring-boot-starter提供了SpringCloudServiceInstanceChooser實(shí)現(xiàn),用戶只需將其配置成SpringBean即可。

          關(guān)注公眾號(hào),學(xué)習(xí)更多 Java 干貨!

          @Bean
          @Autowired
          public ServiceInstanceChooser serviceInstanceChooser(LoadBalancerClient loadBalancerClient) {
              return new SpringCloudServiceInstanceChooser(loadBalancerClient);
          }
          使用@RetrofitserviceIdpath屬性,可以實(shí)現(xiàn)微服務(wù)之間的HTTP調(diào)用
          @RetrofitClient(serviceId = "${jy-helicarrier-api.serviceId}", path = "/m/count", errorDecoder = HelicarrierErrorDecoder.class)
          @Retry
          public interface ApiCountService 
          {

          }

          調(diào)用適配器和數(shù)據(jù)轉(zhuǎn)碼器

          調(diào)用適配器

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

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

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

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

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

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

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

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

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

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

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

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

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

          我們也可以通過繼承CallAdapter.Factory擴(kuò)展實(shí)現(xiàn)自己的CallAdapter

          retrofit-spring-boot-starter支持通過retrofit.global-call-adapter-factories配置全局調(diào)用適配器工廠,工廠實(shí)例優(yōu)先從Spring容器獲取,如果沒有獲取到,則反射創(chuàng)建。默認(rèn)的全局調(diào)用適配器工廠是[BodyCallAdapterFactory, ResponseCallAdapterFactory]

          retrofit:
            # 全局調(diào)用適配器工廠
            global-call-adapter-factories:
              - com.github.lianjiatech.retrofit.spring.boot.core.BodyCallAdapterFactory
              - com.github.lianjiatech.retrofit.spring.boot.core.ResponseCallAdapterFactory

          針對(duì)每個(gè)Java接口,還可以通過@RetrofitClient注解的callAdapterFactories()指定當(dāng)前接口采用的CallAdapter.Factory,指定的工廠實(shí)例依然優(yōu)先從Spring容器獲取。

          注意:如果CallAdapter.Factory沒有public的無參構(gòu)造器,請(qǐng)手動(dòng)將其配置成Spring容器的Bean對(duì)象

          數(shù)據(jù)轉(zhuǎn)碼器

          Retrofit使用Converter@Body注解標(biāo)注的對(duì)象轉(zhuǎn)換成請(qǐng)求體,將響應(yīng)體數(shù)據(jù)轉(zhuǎn)換成一個(gè)Java對(duì)象,可以選用以下幾種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
          • JAXB: com.squareup.retrofit2:converter-jaxb

          retrofit-spring-boot-starter支持通過retrofit.global-converter-factories配置全局?jǐn)?shù)據(jù)轉(zhuǎn)換器工廠,轉(zhuǎn)換器工廠實(shí)例優(yōu)先從Spring容器獲取,如果沒有獲取到,則反射創(chuàng)建。默認(rèn)的全局?jǐn)?shù)據(jù)轉(zhuǎn)換器工廠是retrofit2.converter.jackson.JacksonConverterFactory,你可以直接通過spring.jackson.*配置jackson序列化規(guī)則,配置可參考Customize the Jackson ObjectMapper!

          retrofit:
            # 全局轉(zhuǎn)換器工廠
            global-converter-factories:
              - retrofit2.converter.jackson.JacksonConverterFactory

          針對(duì)每個(gè)Java接口,還可以通過@RetrofitClient注解的converterFactories()指定當(dāng)前接口采用的Converter.Factory,指定的轉(zhuǎn)換器工廠實(shí)例依然優(yōu)先從Spring容器獲取。

          注意:如果Converter.Factory沒有public的無參構(gòu)造器,請(qǐng)手動(dòng)將其配置成Spring容器的Bean對(duì)象

          總結(jié)

          retrofit-spring-boot-starter一個(gè)適用于SpringBoot項(xiàng)目的輕量級(jí)HTTP客戶端框架,已在線上穩(wěn)定運(yùn)行兩年多,并且已經(jīng)有多個(gè)外部公司也接入使用。

          來源:https://juejin.cn/post/6898485806587969544

          瀏覽 45
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <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>
                  久久精品三级片 | 在线观看免费逼视频 | 国产淫色色色 | 亚洲欧洲免费在线 | 狼友视频入口 |