Ribbon、Feign、Hystrix和Zuul超时重试设置(二)

快来打我* 2022-04-24 12:10 359阅读 0赞

上次写了一篇《Ribbon、Feign、Hystrix和Zuul超时重试设置(一)》,主要讲Ribbon和Feign的超时重试如何设置,这次来记录Hystrix的超时如何设置。

也是有一个服务供远程调用,跟之前一样
eureka-client:

  1. @RequestMapping("/test")
  2. public String test() {
  3. int sleepTime = new Random().nextInt(4000);
  4. System.out.println("sleepTime: " + sleepTime);
  5. try {
  6. Thread.sleep(sleepTime); //模拟网络延迟
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. return "test";
  11. }

service-hystrix服务用来调用eureka-client中的接口
pom.xml:

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.cloud</groupId>
  7. <artifactId>spring-cloud-starter-openfeign</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.cloud</groupId>
  11. <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  12. </dependency>

TestController:

  1. @RestController
  2. public class TestController {
  3. private final TestFeign testFeign;
  4. @Autowired
  5. public TestController(TestFeign testFeign) {
  6. this.testFeign = testFeign;
  7. }
  8. @GetMapping("/test")
  9. public String test() {
  10. return testFeign.test();
  11. }
  12. }

TestFeignService:

  1. @FeignClient(value = "eureka-client", fallback = TestFeignServiceImpl.class)
  2. @Repository
  3. public interface TestFeignService {
  4. @RequestMapping("/test")
  5. String test();
  6. }

TestFeignServiceImpl:

  1. @Component
  2. public class TestFeignServiceImpl implements TestFeignService {
  3. @Override
  4. public String test() {
  5. return "error";
  6. }
  7. }

application.yml

  1. server:
  2. port: 8002
  3. eureka:
  4. client:
  5. serviceUrl:
  6. defaultZone: http://localhost:5000/eureka/
  7. spring:
  8. application:
  9. name: service-hystrix
  10. feign:
  11. hystrix:
  12. enabled: true # 开启
  13. hystrix:
  14. command:
  15. default:
  16. execution:
  17. isolation:
  18. thread:
  19. timeoutInMilliseconds: 10000 # 断路器的超时时间需要大于ribbon的超时时间,不然重试没有意义
  20. ribbon:
  21. ReadTimeout: 2000
  22. ConnectionTimeout: 2000
  23. OkToRetryOnAllOperations: true
  24. MaxAutoRetriesNextServer: 1
  25. MaxAutoRetries: 0

运行如下:
在这里插入图片描述
可以看到,当超时并且重试也超时时,会执行降级逻辑,而不会报错。这里,断路器的超时时间需要大于ribbon的超时时间,不然重试没有意义。比如将一下设置去掉(默认值是1秒)或设置较低

  1. hystrix:
  2. command:
  3. default:
  4. execution:
  5. isolation:
  6. thread:
  7. timeoutInMilliseconds: 10000

运行如下:
在这里插入图片描述
可以看到,第一次超时了并重试一次,第二次没有超时,但是页面已经显示error,执行降级逻辑,是因为远程调用的超时时间已经超过了断路器的超时时间,意思是第一次还没执行完就已经执行降级逻辑返回,虽然后台还在重试。所以断路器的超时时间要大于ribbon的超时时间,不然重试没有意义。

发表评论

表情:
评论列表 (有 0 条评论,359人围观)

还没有评论,来说两句吧...

相关阅读

    相关 超时机制

    网上发现这篇好文章,这里记录学习。 介绍       在实际开发过程中,笔者见过太多故障是因为超时没有设置或者设置的不对而造成的。而这些故障都是因为没有意识到超时设置的