0 day streak
java / intermediate
Snippet

Non-Blocking WebClient Requests with Timeout and Fallback

Spring WebClient provides a fully reactive and non-blocking alternative to RestTemplate. Combining reactive operators like timeout() and onErrorReturn() prevents thread starvation during slow downstream network calls and supplies reliable fallback values asynchronously.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Service
public class CurrencyConversionService {
private final WebClient webClient;
public CurrencyConversionService(WebClient.Builder builder) {
this.webClient = builder.baseUrl("https://api.fxrates.example.com").build();
}
public Mono<BigDecimal> fetchExchangeRate(String currency) {
return webClient.get()
.uri("/rates/{currency}", currency)
.retrieve()
.bodyToMono(BigDecimal.class)
.timeout(Duration.ofMillis(1500))
.onErrorReturn(TimeoutException.class, BigDecimal.ONE);
}
}
spring
Breakdown
1
private final WebClient webClient;
Declares the immutable, reactive HTTP client instance.
2
.bodyToMono(BigDecimal.class)
Decodes the response body asynchronously into a single-element Project Reactor Mono stream.
3
.timeout(Duration.ofMillis(1500))
Emits a TimeoutException if the remote service does not reply within 1.5 seconds.
4
.onErrorReturn(TimeoutException.class, BigDecimal.ONE)
Catches the timeout exception and safely defaults to a known base exchange rate.