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

          扔掉okhttp、httpClient,來試試這款輕量級HTTP客戶端神器?

          共 5978字,需瀏覽 12分鐘

           ·

          2020-12-22 11:23

          點擊上方藍(lán)色“程序猿DD”,選擇“設(shè)為星標(biāo)”

          回復(fù)“資源”獲取獨家整理的學(xué)習(xí)資料!

          作者 |?伍陸七

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

          SpringBoot項目直接使用okhttphttpClient或者RestTemplate發(fā)起HTTP請求,既繁瑣又不方便統(tǒng)一管理。因此,在這里推薦一個適用于SpringBoot項目的輕量級HTTP客戶端框架retrofit-spring-boot-starter,使用非常簡單方便,同時又提供諸多功能增強。目前項目已經(jīng)更新至2.2.2版本,并且會持續(xù)進行迭代優(yōu)化。

          github項目地址:

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

          gitee項目地址:

          https://gitee.com/lianjiatech/retrofit-spring-boot-starter

          前言

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

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

          ?項目持續(xù)優(yōu)化迭代,歡迎大家提ISSUE和PR!麻煩大家能給一顆star?,您的star是我們持續(xù)更新的動力!

          功能特性

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

          快速使用

          引入依賴

          <dependency>
          ????<groupId>com.github.lianjiatechgroupId>
          ????<artifactId>retrofit-spring-boot-starterartifactId>
          ????<version>2.2.2version>
          dependency>
          復(fù)制代碼

          定義http接口

          接口必須使用@RetrofitClient注解標(biāo)記!http相關(guān)注解可參考官方文檔:https://square.github.io/retrofit/。

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

          ????@GET("person")
          ????Result?getPerson(@Query("id")?Long?id);
          }
          復(fù)制代碼

          注入使用

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

          @Service
          public?class?TestService?{

          ????@Autowired
          ????private?HttpApi?httpApi;

          ????public?void?test()?{
          ????????//?通過httpApi發(fā)起http請求
          ????}
          }
          復(fù)制代碼

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

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

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

          配置項說明

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

          配置默認(rèn)值說明
          enable-logtrue啟用日志打印
          logging-interceptorDefaultLoggingInterceptor日志打印攔截器
          pool
          連接池配置
          disable-void-return-typefalse禁用java.lang.Void返回類型
          retry-interceptorDefaultRetryInterceptor請求重試攔截器
          global-converter-factoriesJacksonConverterFactory全局轉(zhuǎn)換器工廠
          global-call-adapter-factoriesBodyCallAdapterFactory,ResponseCallAdapterFactory全局調(diào)用適配器工廠
          enable-degradefalse是否啟用熔斷降級
          degrade-typesentinel熔斷降級實現(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
          ??#?請求重試攔截器
          ??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
          ??#?是否啟用熔斷降級
          ??enable-degrade:?true
          ??#?熔斷降級實現(xiàn)方式
          ??degrade-type:?sentinel
          ??#?熔斷資源名稱解析器
          ??resource-name-parser:?com.github.lianjiatech.retrofit.spring.boot.degrade.DefaultResourceNameParser
          復(fù)制代碼

          高級功能

          自定義注入OkHttpClient

          通常情況下,通過@RetrofitClient注解屬性動態(tài)創(chuàng)建OkHttpClient對象能夠滿足大部分使用場景。但是在某些情況下,用戶可能需要自定義OkHttpClient,這個時候,可以在接口上定義返回類型是OkHttpClient.Builder的靜態(tài)方法來實現(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?getPerson(@Url?String?url,?@Query("id")?Long?id);
          }
          復(fù)制代碼

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

          注解式攔截器

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

          1. 繼承BasePathMatchInterceptor編寫攔截處理器;
          2. 接口上使用@Intercept進行標(biāo)注。如需配置多個攔截器,在接口上標(biāo)注多個@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);
          ????}
          }

          復(fù)制代碼
          接口上使用@Intercept進行標(biāo)注
          @RetrofitClient(baseUrl?=?"${test.baseUrl}")
          @Intercept(handler?=?TimeStampInterceptor.class,?include?=?{"/api/**"},?exclude?=?"/api/test/savePerson")
          public?interface?HttpApi?{

          ????@GET("person")
          ????Result?getPerson(@Query("id")?Long?id);

          ????@POST("savePerson")
          ????Result?savePerson(@Body?Person?person);
          }
          復(fù)制代碼

          上面的@Intercept配置表示:攔截HttpApi接口下/api/**路徑下(排除/api/test/savePerson)的請求,攔截處理器使用TimeStampInterceptor

          擴展注解式攔截器

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

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

          例如我們需要在請求頭里面動態(tài)加入accessKeyIdaccessKeySecret簽名信息才能正常發(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容器獲取對應(yīng)的Bean,如果獲取不到,則使用反射創(chuàng)建一個!
          ?????*
          ?????*?@return
          ?????*/

          ????Class?handler()?default?SignInterceptor.class;
          }
          復(fù)制代碼

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

          1. 自定義攔截注解必須使用@InterceptMark標(biāo)記。
          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);
          ????}
          }
          復(fù)制代碼

          上述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?getPerson(@Query("id")?Long?id);

          ????@POST("savePerson")
          ????Result?savePerson(@Body?Person?person);
          }
          復(fù)制代碼

          這樣就能在指定url的請求上,自動加上簽名信息了。

          連接池管理

          默認(rèn)情況下,所有通過Retrofit發(fā)送的http請求都會使用max-idle-connections=5 keep-alive-second=300的默認(rèn)連接池。當(dāng)然,我們也可以在配置文件中配置多個自定義的連接池,然后通過@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
            復(fù)制代碼
          2. 通過@RetrofitClientpoolName屬性來指定使用的連接池。

            @RetrofitClient(baseUrl?=?"${test.baseUrl}",?poolName="test1")
            public?interface?HttpApi?{

            ????@GET("person")
            ????Result?getPerson(@Query("id")?Long?id);
            }
            復(fù)制代碼

          日志打印

          很多情況下,我們希望將http請求日志記錄下來。通過retrofit.enableLog配置可以全局控制日志是否開啟。針對每個接口,可以通過@RetrofitClientenableLog控制是否開啟,通過logLevellogStrategy,可以指定每個接口的日志打印級別以及日志打印策略。retrofit-spring-boot-starter支持了5種日志打印級別(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)然,你也可以自定義實現(xiàn)自己的日志打印攔截器,只需要繼承BaseLoggingInterceptor(具體可以參考DefaultLoggingInterceptor的實現(xiàn)),然后在配置文件中進行相關(guān)配置即可。

          retrofit:
          ??#?日志打印攔截器
          ??logging-interceptor:?com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor
          復(fù)制代碼

          請求重試

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

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

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

          retrofit:
          ??#?請求重試攔截器
          ??retry-interceptor:?com.github.lianjiatech.retrofit.spring.boot.retry.DefaultRetryInterceptor
          復(fù)制代碼

          錯誤解碼器

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

          /**
          ?*?錯誤解碼器。ErrorDecoder.
          ?*?當(dāng)請求發(fā)生異常或者收到無效響應(yīng)結(jié)果的時候,將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)的時候,將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)請求發(fā)生IO異常時,將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)請求發(fā)生除IO異常之外的其它異常時,將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);
          ????}

          }

          復(fù)制代碼

          全局?jǐn)r截器

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

          如果我們需要對整個系統(tǒng)的的http請求執(zhí)行統(tǒng)一的攔截處理,可以自定義實現(xiàn)全局?jǐn)r截器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);
          ????}
          }
          復(fù)制代碼

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

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

          熔斷降級

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

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

          1. 開啟熔斷降級功能

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

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

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

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

          <dependency>
          ????<groupId>com.alibaba.cspgroupId>
          ????<artifactId>sentinel-coreartifactId>
          ????<version>1.6.3version>
          dependency>
          復(fù)制代碼
          2. 配置降級規(guī)則(可選)

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

          @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;
          }
          復(fù)制代碼

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

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

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

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

          @Slf4j
          @Service
          public?class?HttpDegradeFallback?implements?HttpDegradeApi?{

          ????@Override
          ????public?Result?test()?{
          ????????Result?fallback?=?new?Result<>();
          ????????fallback.setCode(100)
          ????????????????.setMsg("fallback")
          ????????????????.setBody(1000000);
          ????????return?fallback;
          ????}
          }
          復(fù)制代碼
          @Slf4j
          @Service
          public?class?HttpDegradeFallbackFactory?implements?FallbackFactory<HttpDegradeApi>?{

          ????/**
          ?????*?Returns?an?instance?of?the?fallback?appropriate?for?the?given?cause
          ?????*
          ?????*?@param?cause?fallback?cause
          ?????*?@return?實現(xiàn)了retrofit接口的實例。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?test()?{
          ????????????????Result?fallback?=?new?Result<>();
          ????????????????fallback.setCode(100)
          ????????????????????????.setMsg("fallback")
          ????????????????????????.setBody(1000000);
          ????????????????return?fallback;
          ????????????}
          ????}
          }
          復(fù)制代碼

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

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

          配置ServiceInstanceChooserSpring容器Bean

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

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

          }
          復(fù)制代碼

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

          調(diào)用適配器

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

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

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

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

          ????@GET("person")
          ????Call>?getPersonCall(@Query("id")?Long?id);

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

          ????@GET("person")
          ????CompletableFuture>?getPersonCompletableFuture(@Query("id")?Long?id);

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

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

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

          ????@GET("person")
          ????Response>?getPersonResponse(@Query("id")?Long?id);

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

          ????@GET("person")
          ????Result?getPerson(@Query("id")?Long?id);

          復(fù)制代碼

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

          retrofit-spring-boot-starter支持通過retrofit.global-call-adapter-factories配置全局調(diào)用適配器工廠,工廠實例優(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
          復(fù)制代碼

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

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

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

          Retrofit使用Converter@Body注解標(biāo)注的對象轉(zhuǎn)換成請求體,將響應(yīng)體數(shù)據(jù)轉(zhuǎn)換成一個Java對象,可以選用以下幾種Converter

          • Gson(https://github.com/google/gson): com.squareup.Retrofit:converter-gson
          • Jackson(https://github.com/FasterXML/jackson): com.squareup.Retrofit:converter-jackson
          • Moshi(https://github.com/square/moshi/): com.squareup.Retrofit:converter-moshi
          • Protobuf(https://developers.google.com/protocol-buffers/): com.squareup.Retrofit:converter-protobuf
          • Wire(https://github.com/square/wire): com.squareup.Retrofit:converter-wire
          • Simple XML(http://simple.sourceforge.net/): com.squareup.Retrofit:converter-simplexml
          • JAXB(https://docs.oracle.com/javase/tutorial/jaxb/intro/index.html): com.squareup.retrofit2:converter-jaxb

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

          retrofit:
          ??#?全局轉(zhuǎn)換器工廠
          ??global-converter-factories:
          ????-?retrofit2.converter.jackson.JacksonConverterFactory
          復(fù)制代碼

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

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

          總結(jié)

          retrofit-spring-boot-starter一個適用于SpringBoot項目的輕量級HTTP客戶端框架,已在線上穩(wěn)定運行一年多,并且已經(jīng)有多個外部公司也接入使用。有興趣的朋友可以嘗試一下。

          DD自研的滬牌代拍業(yè)務(wù),點擊直達(dá)


          【往期推薦】

          居然還有這種游戲...是不是有點刺激過頭了啊...

          2020-12-19

          Spring Boot 2.4版本前后的分組配置變化及對多環(huán)境配置結(jié)構(gòu)的影響

          2020-12-19

          贊!推薦一款神仙顏值的 Redis 客戶端工具

          2020-12-19

          左滑右滑,在VS Code里滑個妹紙給你寫喜歡的代碼?

          2020-12-18

          教你一分鐘內(nèi)導(dǎo)出 Grafana 所有的 Dashboard

          2020-12-18

          注意!我們熟知的“摩爾定律”被廢了...

          2020-12-17



          掃一掃,關(guān)注我

          知曉前沿科技,領(lǐng)略技術(shù)魅力

          深度內(nèi)容

          推薦加入


          歡迎加入知識星球,一起探討技術(shù)架構(gòu),交流技術(shù)人生。
          加入方式,長按下方二維碼:
          已在知識星球更新如下:

          素質(zhì)二連,走一個


          瀏覽 82
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

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

          手機掃一掃分享

          分享
          舉報
          <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>
                  国产无码一二三 | a在线视频免费 | 囯产精品久久久久久久久久辛辛 | a免费观看 | 五月天俺也去婷婷 |