溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

一文詳解Spring Cloud Feign重試機制

發布時間:2020-07-26 11:53:04 來源:網絡 閱讀:1131 作者:愛碼仕i 欄目:編程語言

前言

Feign組件默認使用Ribbon的重試機制并增加了根據狀態碼判斷重試機制,默認情況下是不啟用的。Feign使用的是Spring Retry組件,需要引入依賴才能啟用。

一、POM引入Spring Retry

<dependency>
        <groupId>org.springframework.retry</groupId>
        <artifactId>spring-retry</artifactId>
  </dependency>

二、配置文件

eureka-client:
   ribbon:
      MaxAutoRetries: 1
      MaxAutoRetriesNextServer: 1
      retryableStatusCodes: 500,404 
      OkToRetryOnAllOperations: true 
      NFLoadBalancerRuleClassName: com.netflix.loadbalancer.AvailabilityFilteringRule #負載均衡規則

eureka-client是自己的serverId,MaxAutoRetries同一臺服務器上的最大重試次數(不包括第一次嘗試),MaxAutoRetriesNextServer要重試的下一個服務器的最大數量(不包括第一個服務器),retryableStatusCodes可以根據接口返回的狀態碼判斷是否重試其他服務,OkToRetryOnAllOperations只對所有的超時請求重試

注意: Ribbon的重試機制只有對GET請求或者設置了OkToRetryOnAllOperations生效 詳情請查看源碼:

public class RibbonLoadBalancedRetryPolicy implements LoadBalancedRetryPolicy {
    ...
        public Boolean canRetry(LoadBalancedRetryContext context) {
        HttpMethod method = context.getRequest().getMethod();
        return HttpMethod.GET == method || lbContext.isOkToRetryOnAllOperations();
    }
    ...
}

Feign對返回狀態碼做了重試判斷RetryableFeignLoadBalancer

public class RetryableFeignLoadBalancer extends FeignLoadBalancer
    implements ServiceInstanceChooser {
    ...
        [@Override](https://my.oschina.net/u/1162528)
    public RibbonResponse execute(final RibbonRequest request,
                IClientConfig configOverride) throws IOException {
        ...
                if (retryPolicy != null
                                && retryPolicy.retryableStatusCode(response.status())) {
            byte[] byteArray = response.body() == null ? new byte[] {}
                                        : StreamUtils
                                                .copyToByteArray(response.body().asInputStream());
            response.close();
            throw new RibbonResponseStatusCodeException(
                                        RetryableFeignLoadBalancer.this.clientName, response,
                                        byteArray, request.getUri());
        }
        ...
    }
    ...
}

重試機制用的是Spring Retry組件當拋出異常時進行重試!

GET請求指的是feign client 請求其他client時聲明的那個interface中mapping注解類型,RequestMapping不設置method默認為GET請求

@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
        List<Store> getStores();
    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
        Store update(@PathVariable("storeId") long storeId, Store store);
}

寫在最后

  • 第一:看完點贊,感謝您對作者的認可;
  • ...
  • 第二:隨手轉發,分享知識,讓更多人學習到;
  • ...
  • 第三:記得點關注,每天更新的?。?!
  • ...

一文詳解Spring Cloud Feign重試機制

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女