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

我想将两者结合起来:当断路器状态为闭合时,将在跌落之前重试3次(以应对瞬态错误),如果该状态为断开,则将直接跌落。

有什么优雅的方法吗?一种可行的方法是在函数内部实现重试逻辑,但我认为这不是最佳解决方案。

最佳答案

@CircuitBreaker已经将@Retry实现为有状态= 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();
    }
  });
}

声明RetryTemplate:
@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 { ... }

10-02 05:43