Feign組件默認使用Ribbon的重試機制并增加了根據狀態碼判斷重試機制,默認情況下是不啟用的。Feign使用的是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);
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。