【问题标题】:How to combine Retryable and CircuitBreaker together in Spring?如何在 Spring 中将 Retryable 和 CircuitBreaker 结合在一起?
【发布时间】:2017-12-03 14:44:34
【问题描述】:

Spring 的 @Retryable 注解将重试 3 次(默认)并回退到 @Recovery 方法。但是,@CircuitBreaker 会重试一次,并在状态关闭时回退。

我想把这两个结合起来:当断路器状态关闭时,会在回退前重试3次(处理瞬态错误),如果状态打开,则直接回退。

有什么优雅的方法可以做到这一点?一种可能的方法是在函数内部实现重试逻辑,但我觉得这不是最好的解决方案。

【问题讨论】:

    标签: java spring spring-retry circuit-breaker retrypolicy


    【解决方案1】:

    @CircuitBreaker 已经将 @Retry 实现为 stateful = true,这就是他知道多少次调用失败的方式。

    我认为最好的方法是在您的方法中使用 RetryTemplate:

    @CircuitBreaker(maxAttempts = 2, openTimeout = 5000l, resetTimeout = 10000l)
    void call() {
      retryTemplate.execute(new RetryCallback<Void, RuntimeException>() {
        @Override
        public Void doWithRetry(RetryContext context) {
          myService.templateRetryService();
        }
      });
    }
    

    声明重试模板:

    @Configuration
    public class AppConfig {
    
      @Bean
      public RetryTemplate retryTemplate() {
          RetryTemplate retryTemplate = new RetryTemplate();
    
          FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
          fixedBackOffPolicy.setBackOffPeriod(2000l);
          retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
    
          SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
          retryPolicy.setMaxAttempts(2);
          retryTemplate.setRetryPolicy(retryPolicy);
    
          return retryTemplate;
      }
    }
    

    在项目中启用 Spring Retry:

    @Configuration
    @EnableRetry
    public class AppConfig { ... }
    

    【讨论】:

    • 实施从断路器重试时,断路器只有在重试完成后才会看到错误。在这种方法中,必须仔细设置阈值。理想情况下,要打开的电路代理的阈值应该更小。请检查,对于您的应用,断路器应该在内部重试还是在外部。
    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 2020-09-23
    • 1970-01-01
    • 2022-12-19
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多