Sub topic 11
Calling other services with WebClient
This chapter assumes you can write Mono and Flux pipelines with map and flatMap. It also assumes you know how an annotated controller returns a Mono. Here you will call another HTTP service without blocking an event-loop thread.
What WebClient is
WebClient is Spring's non-blocking HTTP client. It replaces RestTemplate in reactive code. A RestTemplate call holds a thread until the response arrives. A WebClient call returns a Mono or Flux at once and frees the thread. The request is sent only when something subscribes.
Building a client
Create one client per remote service and reuse it. In a Spring Boot application, inject the auto-configured WebClient.Builder so your codecs and metrics settings apply.
WebClient client = WebClient.builder()
.baseUrl("https://api.example.com")
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.build();Sending a request and reading the body
A call has three stages: describe the request, call retrieve(), then choose how to read the body.
WebClient client = WebClient.create("https://api.example.com");
Mono<User> user = client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class)
.timeout(Duration.ofSeconds(2))
.retryWhen(Retry.backoff(3, Duration.ofMillis(200)));- Use
bodyToMonowhen you expect zero or one object. - Use
bodyToFluxwhen you expect a sequence. - The URI template
/users/{id}encodes the variable for you. Do not concatenate strings.
Handling HTTP error statuses
By default, retrieve() turns any 4xx or 5xx response into a WebClientResponseException that travels down the pipeline as an error signal. You can replace it with onStatus, or recover from specific cases with onErrorResume.
Mono<User> findUser(String id) {
return client.get()
.uri("/users/{id}", id)
.retrieve()
.onStatus(HttpStatusCode::is5xxServerError,
response -> Mono.error(new ResponseStatusException(HttpStatus.BAD_GATEWAY)))
.bodyToMono(User.class)
.onErrorResume(WebClientResponseException.NotFound.class, ex -> Mono.empty());
}Here a 404 from the remote service becomes an empty Mono. A 5xx becomes a 502 from your own service.
Combining several calls
Independent calls should run at the same time. Mono.zip subscribes to all its sources together and emits when every one has produced a value.
@Service
public class ProfileService {
private final WebClient client;
public ProfileService(WebClient.Builder builder) {
this.client = builder.baseUrl("https://api.example.com").build();
}
public Mono<Profile> load(String id) {
Mono<User> user = client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class);
Mono<List<Order>> orders = client.get()
.uri("/users/{id}/orders", id)
.retrieve()
.bodyToFlux(Order.class)
.collectList();
return Mono.zip(user, orders)
.map(tuple -> new Profile(tuple.getT1(), tuple.getT2()));
}
}
record Profile(User user, List<Order> orders) {}Use flatMap instead when the second call needs the result of the first.
Common errors
- Nothing happens. If you never subscribe, no request goes out. Return the
Monofrom your controller so the framework subscribes. - Calling
block()inside a handler. This stalls an event-loop thread. Keep the chain reactive from the call to the controller's return value. - Retrying everything.
Retry.backoffretries on every error by default, including 4xx responses that will never succeed. Add.filter(...)to retry only transient failures such as 5xx or connection errors. - Creating a new client per request. This wastes connection pools. Build the client once.
- Unbounded waits. Without
timeout, a slow remote service holds your request open indefinitely.
Exercise
A handler calls /users/{id} and then /users/{id}/orders, and the second URL does not depend on the first result. Which operator should you use to run both calls at once, and why not flatMap?
Show answer
Use Mono.zip on the two Monos. It subscribes to both immediately, so the calls overlap. flatMap would subscribe to the second call only after the first one finished, so the total latency would be the sum of the two calls.