前言
Feign組件默認(rèn)使用Ribbon的重試機(jī)制并增加了根據(jù)狀態(tài)碼判斷重試機(jī)制,默認(rèn)情況下是不啟用的。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 #負(fù)載均衡規(guī)則
eureka-client是自己的serverId,MaxAutoRetries同一臺(tái)服務(wù)器上的最大重試次數(shù)(不包括第一次嘗試),MaxAutoRetriesNextServer要重試的下一個(gè)服務(wù)器的最大數(shù)量(不包括第一個(gè)服務(wù)器),retryableStatusCodes可以根據(jù)接口返回的狀態(tài)碼判斷是否重試其他服務(wù),OkToRetryOnAllOperations只對(duì)所有的超時(shí)請(qǐng)求重試
注意: Ribbon的重試機(jī)制只有對(duì)GET請(qǐng)求或者設(shè)置了OkToRetryOnAllOperations生效 詳情請(qǐng)查看源碼:
public class RibbonLoadBalancedRetryPolicy implements LoadBalancedRetryPolicy {
...
public Boolean canRetry(LoadBalancedRetryContext context) {
HttpMethod method = context.getRequest().getMethod();
return HttpMethod.GET == method || lbContext.isOkToRetryOnAllOperations();
}
...
}
Feign對(duì)返回狀態(tài)碼做了重試判斷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());
}
...
}
...
}
重試機(jī)制用的是Spring Retry組件當(dāng)拋出異常時(shí)進(jìn)行重試!
GET請(qǐng)求指的是feign client 請(qǐng)求其他client時(shí)聲明的那個(gè)interface中mapping注解類型,RequestMapping不設(shè)置method默認(rèn)為GET請(qǐng)求
@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);
}
寫(xiě)在最后
- 第一:看完點(diǎn)贊,感謝您對(duì)作者的認(rèn)可;
- ...
- 第二:隨手轉(zhuǎn)發(fā),分享知識(shí),讓更多人學(xué)習(xí)到;
- ...
- 第三:記得點(diǎn)關(guān)注,每天更新的?。。?/strong>
- ...
