Why Retry is not triggered when I use resilience4j functional configuration?

415 Views Asked by At

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 ?

2

There are 2 best solutions below

0
gstackoverflow On BEST ANSWER

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();
1
Nikolas Charalambidis On

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: