ribbon 重试

2019-02-17  本文已影响9人  王小杰at2019

ribbon 重试

Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用。Spring Cloud Ribbon虽然只是一个工具类框架,它不像服务注册中心、配置中心、API网关那样需要独立部署,但是它几乎存在于每一个Spring Cloud构建的微服务和基础设施中。因为微服务间的调用,API网关的请求转发等内容,实际上都是通过Ribbon来实现的,包括后续我们将要介绍的Feign,它也是基于Ribbon实现的工具。

重试配置

ribbon:
  # 服务最大重试次数,不包含第一次请求
  MaxAutoRetries: 5
  # 负载均衡切换次数,如果服务注册列表小于 nextServer count 那么会循环请求  A > B > A
  MaxAutoRetriesNextServer: 3
  #是否所有操作都进行重试
  OkToRetryOnAllOperations: false
  

更多参数配置参考:

com.netflix.client.config.DefaultClientConfigImpl

Ribbon脱离Eureka使用,声明服务test

test:
  ribbon:
    listOfServers: http://localhost:8080,http://127.0.0.1:8080

创建 FeignClient


@FeignClient(name = "test" )
public interface RetryFeignTestClient {

    @GetMapping("/")
    String retry();

}

创建一个服务来验证一下配置


@RestController
@Slf4j
public class TestController {

    @GetMapping("/")
    public String test(HttpServletRequest request) throws InterruptedException {
        log.info("ServerName:{} time:{}", request.getServerName(), DateFormatUtils.format(new Date(), "yyyyMMdd HH:mm:ss"));
        TimeUnit.SECONDS.sleep(120);
        return "ok";

    }
}
 ServerName:localhost time:20190217 14:25:43
 ServerName:localhost time:20190217 14:25:44
 ServerName:localhost time:20190217 14:25:45
 ServerName:localhost time:20190217 14:25:46
 ServerName:localhost time:20190217 14:25:47
 ServerName:localhost time:20190217 14:25:48
 ServerName:127.0.0.1 time:20190217 14:25:49
 ServerName:127.0.0.1 time:20190217 14:25:50
 ServerName:127.0.0.1 time:20190217 14:25:51
 ServerName:127.0.0.1 time:20190217 14:25:52
 ServerName:127.0.0.1 time:20190217 14:25:53
 ServerName:127.0.0.1 time:20190217 14:25:54
 ServerName:localhost time:20190217 14:25:55
 ServerName:localhost time:20190217 14:25:56
 ServerName:localhost time:20190217 14:25:57
 ServerName:localhost time:20190217 14:25:58
 ServerName:localhost time:20190217 14:25:59
 ServerName:localhost time:20190217 14:26:00
 ServerName:127.0.0.1 time:20190217 14:26:01
 ServerName:127.0.0.1 time:20190217 14:26:02
 ServerName:127.0.0.1 time:20190217 14:26:03
 ServerName:127.0.0.1 time:20190217 14:26:04
 ServerName:127.0.0.1 time:20190217 14:26:05
 ServerName:127.0.0.1 time:20190217 14:26:06

输出结果 ,我们可以看到每个服务都请求了6次, 服务请求 的顺序是localhost > 127.0.0.1 > localhost > 127.0.0.1
这个顺序和我们上面配置的顺一致,根据请求结果,可以看到当服务重试5次失败后才会选择 nextServer 执行

注意:

这个时候时候像连接参数超时时间等就不用去配置 Feign 了,如果配置 Feign 会产生冲突,这时候这时候直接配置 ribbon 就好了

OkToRetryOnAllOperations

OkToRetryOnAllOperations
如果该值为 false 那么只对 get 方法请起作用,如果为 true 那么对所有的请求方法起作用, 但是要true要慎用,如果服务端的接口不是幂等接口那么很有可能会产生重复数据

org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer#getRequestSpecificRetryHandler


image.png
上一篇下一篇

猜你喜欢

热点阅读