5

Spring's @Retryable annotation will retry three times (default) and fallback to the @Recovery method. @CircuitBreaker however, will retry once and fall back when the state is closed.

I want to combine these two: when the circuit breaker state is closed, will retry three times before falling back (to deal with transient errors), if the state is open, will directly fall back.

Any elegant way to do this? A possible approach is to implement the retry logic inside the function, but I feel that it wouldn't be the best solution.

Zebing Lin
  • 371
  • 4
  • 6

1 Answers1

2

The @CircuitBreaker already implements @Retry as a stateful = true, that's how he knows how many calls failed.

I think the best approach here, would be use a RetryTemplate inside your method:

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

Declaring the 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;
  }
}

Enabling Spring Retry in the project:

@Configuration
@EnableRetry
public class AppConfig { ... }
Brother
  • 2,150
  • 1
  • 20
  • 24
  • When Retry from Circuit Breaker is implemented, circuit breaker will see errors only after retries are complete. In this approach, thresholds must be carefully set. Ideally threshold values should be lesser for circuit broker to be open. Please check, for your application, circuit breaker should be inside retry or outside. – Prakhyat Jan 15 '20 at 11:14