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); }
群内有技术大咖指点难题,还提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、Jvm性能调优、Spring源码,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料)
比你优秀的对手在学习,你的仇人在磨刀,你的闺蜜在减肥,隔壁老王在练腰, 我们必须不断学习,否则我们将被学习者超越!