How can I add retry and custom recovery method in a circuit breaker - functional java

492 Views Asked by At

I'm trying to add a resilience 4j circuit breaker to my project. For that, I have a custom mechanism if the call fails and a retry. How can I change the execution sequence of these two? Is there a way where I can execute my custom mechanism first and if that also fails then do the retry?

1

There are 1 best solutions below

0
On

If I understood you correctly, you have 2 different calls. The first call you expect to fail sometimes. But instead of retry the first call you want to use the second call. Then, if this second one fails you would like to retry using the circuit breaker.

CircuitBreakerConfig config = CircuitBreakerConfig
    .custom()
    .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
    .slidingWindowSize(10)
    .failureRateThreshold(25.0f)
    .waitDurationInOpenState(Duration.ofSeconds(10))
    .permittedNumberOfCallsInHalfOpenState(4)
    .build();
CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config);
CircuitBreaker circuitBreaker = registry.circuitBreaker("searchService");

try {
    // First call
    service.search(request)
} catch (SearchException e) {
    // Second call using circuit breaker
    Supplier<List<SearchPojo>> searchSupplier = circuitBreaker
        .decorateSupplier(() -> service.search(request, a_new_parameter));
}