0 day streak
java / expert
Snippet

ExchangeFilterFunction for Global Resilience in WebClient

ExchangeFilterFunctions act as interceptors for WebClient, allowing you to implement cross-cutting concerns like logging, retries, or auth token injection for all outgoing reactive requests.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public ExchangeFilterFunction retryFilter() {
return (request, next) -> next.exchange(request)
.flatMap(response -> {
if (response.statusCode().is5xxServerError()) {
return Mono.error(new RuntimeException("Server Error"));
}
return Mono.just(response);
})
.retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(2)));
}
@Bean
public WebClient webClient() {
return WebClient.builder()
.filter(retryFilter())
.build();
}
spring
Breakdown
1
next.exchange(request)
Continues the request chain to the next filter or the final network call.
2
retryWhen(Retry.fixedDelay(...))
Configures a reactive retry strategy for failed requests based on the defined duration.