1

I had successful experiments with spring boot configuration for resillence4j but I want to try functional configuration.

So I have implemented following code:

    RetryConfig config = RetryConfig.custom()
            .maxAttempts(6)
            .waitDuration(Duration.ofMillis(100))
            .build();

    RetryRegistry registry = RetryRegistry.of(config);

    Retry retry = registry.retry("name1");
    Retry.decorateCheckedSupplier(retry, myService::bar);

    myService.bar();

@Service
@Slf4j
public class MyService {
    public String bar() throws InterruptedException {
        log.error("Bar is called");
        Thread.sleep(3000);
        if (true) {
            throw new RuntimeException("bar exception");
        }
        return "Success";
    }
}

When I start the application I see single error:

Exception in thread "main" java.lang.RuntimeException: bar exception

Why retry was not triggered ?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • As per 1st snap code you are calling direct service due to this retry seems to be ignored, to execute can't we use get() function to execute retry like Retry.decorateCheckedSupplier(retry, myService::bar).get(); – Raushan Kumar Apr 18 '23 at 11:18

2 Answers2

0

Since you use Spring Boot, there is no need for manual configuring of RetryConfig, the RetryRegistry registry, etc. All the configuration is handled by the framework as you define entries only in application.yml.

resilience4j:
  retry:
    instances:
      retry-bar:              # custom backend instance name definition
        maxRetryAttempts: 5
        waitDuration: 100ms

If you don't do it and you want to stick with RetryConfig and other configuration classes, you have to define them all as @Bean in the @Configuration class and make sure they are component-scanned by Spring.


To apply the retry configuration, annotate the method bar with the @Retry annotation to suggest the method should be decorated with the retry mechanism:

@Retry("retry-bar")
public String bar() throws InterruptedException {
    log.error("Bar is called");
    Thread.sleep(3000);
    if (true) {
        throw new RuntimeException("bar exception");
    }
    return "Success";
}

Reference:

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • Based on information I've read functiona style is more flexible. What if I want to have cicuite breaker over retry for endpoint#1 and retry over cicuite breaker fpr endpoint#2 ? looks like spring boot config doesn't support it – gstackoverflow Apr 18 '23 at 12:32
0

The issue was that I had to use decorator instead of raw function. Correct implemtation is:

CheckedFunction0<String> decoratedFunction = Retry.decorateCheckedSupplier(retry, myService::bar);
decoratedFunction.apply();
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710