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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Servicepublic 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.