Search code examples
spring-cloudresilience4j

spring-cloud-circuitbreaker with reactive resilience4j


I am confused with CircuitBreaker using WebClient. When the dependent service is down it, the fallback is not executed. Do I need additional configuration?

For the CircuitBreaker using RestTemplate this is working without any further configuration. See my example code here: https://github.com/altfatterz/resilience4j-demo

Here is my example

    @GetMapping("/")
    public Mono<String> hello() {
        return webClient.build()
                .get().uri(uriBuilder -> uriBuilder
                        .scheme("http")
                        .host("slow-service").path("/slow")
                        .build())
                .retrieve().bodyToMono(String.class).transform(it -> {
                    CircuitBreaker cb = circuitBreakerFactory.create("slow");
                    return cb.run(() -> it, throwable -> Mono.just("fallback"));
                });
    }

using the following configuration:

    @Bean
    public Customizer<ReactiveResilience4JCircuitBreakerFactory> defaultCustomizer() {
        return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
                .circuitBreakerConfig(ofDefaults())
                .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(3)).build()).build());
    }

    @Bean
    @LoadBalanced
    public WebClient.Builder webClient() {
        return WebClient.builder();
    }



Solution

  • The problem is here https://github.com/altfatterz/resilience4j-demo/blob/master/slow-service-reactive-client/src/main/java/com/example/SlowServiceReactiveClientApplication.java#L27

    and here https://github.com/altfatterz/resilience4j-demo/blob/master/slow-service-reactive-client/src/main/java/com/example/SlowServiceReactiveClientApplication.java#L43

    Since you are using WebClient you need to use a ReactiveCircuitBreakerFactory and a ReactiveCircuitBreaker.