一文详解Spring Cloud Feign重试机制

前言

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重试机制

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值