0 day streak
java / intermediate
Snippet

Non-blocking HTTP Requests using WebClient

WebClient is the modern, non-blocking alternative to RestTemplate in Spring. It supports reactive programming, allowing your application to handle many concurrent requests without blocking threads, improving scalability.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Service
public class RemoteClient {
private final WebClient webClient;
public RemoteClient(WebClient.Builder builder) {
this.webClient = builder.baseUrl("https://api.example.com").build();
}
public Mono<User> getUser(String id) {
return webClient.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class)
.timeout(Duration.ofSeconds(3));
}
}
spring
Breakdown
1
Mono<User>
A reactive type representing a single asynchronous result (0 or 1).
2
bodyToMono(User.class)
Automatically deserializes the JSON response body into a Java object.
3
timeout(Duration.ofSeconds(3))
Ensures the request fails if it takes longer than the specified duration.