Sub topic 13
Reactive clients with WebClient
This chapter assumes you have built a declarative client with RestClient and HttpServiceProxyFactory, and that you know the basics of Project Reactor: Mono is a publisher of zero or one value, and Flux is a publisher of zero or more values. Nothing happens until something subscribes.
The interface style you already know carries over almost unchanged. You swap the transport from RestClient to WebClient and change the return types to reactive ones.
What changes and what stays the same
An @HttpExchange interface describes the API. The adapter you give the factory decides how calls are executed.
| Part | Blocking client | Reactive client |
|---|---|---|
| Transport | `RestClient` | `WebClient` |
| Adapter | `RestClientAdapter` | `WebClientAdapter` |
| Builder bean | `RestClient.Builder` | `WebClient.Builder` |
| Return types | `Todo`, `List<Todo>`, `ResponseEntity<Todo>` | `Mono<Todo>`, `Flux<Todo>`, `Mono<ResponseEntity<Todo>>` |
| Error signal | Thrown `HttpClientErrorException` | `WebClientResponseException` delivered as an error signal |
Annotations and argument binding (@PathVariable, @RequestParam, @RequestHeader, @RequestBody) behave the same in both. Only the return types and the error delivery differ.
To use WebClient, add spring-boot-starter-webflux to your build. If the project also has spring-boot-starter-web, the application stays a servlet application. WebClient is then only used as an HTTP client, which is a supported setup.
Declaring a reactive interface
This interface describes the same todo API as before, with reactive return types.
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.service.annotation.DeleteExchange;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@HttpExchange("/todos")
public interface ReactiveTodoClient {
@GetExchange("/{id}")
Mono<Todo> getTodo(@PathVariable long id);
@GetExchange
Flux<Todo> listByUser(@RequestParam long userId);
@PostExchange
Mono<ResponseEntity<Todo>> create(@RequestBody Todo todo);
@DeleteExchange("/{id}")
Mono<Void> delete(@PathVariable long id);
}Todo is the record from the earlier chapters.
The return types work as follows:
Mono<Todo>emits the decoded body once, or an error signal for a 4xx or 5xx status.Flux<Todo>decodes a JSON array into a stream of elements. Fortext/event-streamresponses it emits one element per event.Mono<ResponseEntity<Todo>>gives you status and headers along with the body. Use it when you need aLocationheader or want to branch on the status.Mono<Void>completes when the response arrives and discards the body. It is the usual choice forDELETE.Mono<HttpHeaders>completes with the response headers only.
The @RequestBody argument can also be a Publisher, such as Mono<Todo> or Flux<Todo>. WebClient then subscribes to it and streams the encoded elements into the request. The blocking adapter cannot do this.
Building the proxy with WebClientAdapter
The factory code has the same shape as the RestClient version. Spring Boot auto-configures a WebClient.Builder bean. It is prototype-scoped, so each injection point gets a fresh builder, and it already carries Boot's codecs and any WebClientCustomizer beans.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
@Configuration
class ReactiveTodoClientConfig {
@Bean
ReactiveTodoClient reactiveTodoClient(WebClient.Builder builder) {
WebClient webClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
HttpServiceProxyFactory factory = HttpServiceProxyFactory
.builderFor(WebClientAdapter.create(webClient))
.build();
return factory.createClient(ReactiveTodoClient.class);
}
}On Spring Framework 6.0, the factory method names were different (HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient))). The builderFor form shown here applies from Spring Framework 6.1, which is what Spring Boot 3.2 and later use.
Reactive and blocking return types
Which return types are allowed depends on the adapter.
WebClientAdaptersupports both reactive return types and plain blocking ones. A method that returnsTodostill works. The proxy subscribes and blocks the calling thread until the response arrives.RestClientAdaptersupports only blocking return types. If an interface declares aMonoorFluxmethod and you build it withRestClientAdapter, the factory rejects it. Pick the adapter to match the interface.
The blocking fallback is convenient in a servlet application that wants one client with both styles. It is dangerous inside a reactive pipeline. Blocking on a Reactor Netty event-loop thread stalls every request that thread serves, and Reactor typically detects this and throws an IllegalStateException on block(). In reactive code, declare reactive return types and keep the chain non-blocking.
Laziness and timing
A method that returns Mono or Flux does not send the request when you call it. The request is sent on subscription, and each subscription sends it again.
Mono<Todo> call = todoClient.getTodo(1); // no HTTP request yet
call.subscribe(); // request 1
call.subscribe(); // request 2, same call objectThis has practical consequences:
- Retrying with
retry()orretryWhen(...)works because resubscription re-sends the request. Only retry idempotent calls such asGET, or calls that the server de-duplicates. - If you call a method and discard the result, nothing is sent. This is a common bug with
Mono<Void>methods such asdelete. - To fire a request once and share the result among several consumers, use
cache()orshare()deliberately.
Timeouts for WebClient
WebClient does not own the connection settings. They belong to the connector, which is ReactorClientHttpConnector over Reactor Netty by default. Configure a Netty HttpClient and pass it to the builder.
import java.time.Duration;
import io.netty.channel.ChannelOption;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
import reactor.netty.http.client.HttpClient;
@Configuration
class TimeoutAwareClientConfig {
@Bean
ReactiveTodoClient timeoutAwareTodoClient(WebClient.Builder builder) {
HttpClient httpClient = HttpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000)
.responseTimeout(Duration.ofSeconds(5));
WebClient webClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
return HttpServiceProxyFactory
.builderFor(WebClientAdapter.create(webClient))
.build()
.createClient(ReactiveTodoClient.class);
}
}There are two layers of timeout:
- Connector timeouts. The connect timeout limits TCP connection setup.
responseTimeoutlimits the wait for the response after the request is sent. Both apply to every call through this client. - Operator timeouts.
mono.timeout(Duration.ofSeconds(3))bounds a single subscription, including time spent waiting for a connection from the pool. It signalsTimeoutExceptionand cancels the in-flight request.
Use connector settings as a safe default and an operator timeout where one call needs a tighter limit. If you register this second bean alongside the first, you now have two ReactiveTodoClient beans of the same type. Use one configuration, or add a qualifier, in a real project.
Default headers and authentication are configured on the builder with defaultHeader(...) and filters, as they were for RestClient. A common reactive pattern is an ExchangeFilterFunction that adds a token. It is the WebClient counterpart of a RestClient request interceptor.
Handling errors
By default, WebClient turns a 4xx or 5xx status into an error signal. The exception is WebClientResponseException or one of its subclasses, such as WebClientResponseException.NotFound. It is not thrown at the call site, so a try/catch around the method call catches nothing. Handle it in the pipeline.
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
@Service
class ReactiveTodoService {
private final ReactiveTodoClient todoClient;
ReactiveTodoService(ReactiveTodoClient todoClient) {
this.todoClient = todoClient;
}
Mono<Todo> findOrEmpty(long id) {
return todoClient.getTodo(id)
.onErrorResume(WebClientResponseException.NotFound.class,
e -> Mono.empty());
}
}An empty Mono here means "no such todo". Callers can use defaultIfEmpty(...) or switchIfEmpty(...) to decide what to do.
Some further points on errors:
- Connection failures and timeouts are not
WebClientResponseException. They arrive asWebClientRequestException(wrapping, for example, a connect or read timeout) or asTimeoutExceptionfrom an operator timeout. Handle them separately from status errors. - If you need the response body of an error,
WebClientResponseException#getResponseBodyAsString()has it. - Setting a custom status handler for all calls is done at the builder level with
defaultStatusHandler(...), which mirrors theRestClientbuilder. Mono<ResponseEntity<Todo>>does not bypass error handling. A 404 still produces an error signal unless you handle it.
Testing a reactive client
MockRestServiceServer works with RestClient and RestTemplate, not with WebClient. For WebClient, either run a local mock HTTP server such as OkHttp's MockWebServer, or stub the ExchangeFunction. The second option needs no extra server. It also needs reactor-test for StepVerifier, which spring-boot-starter-test does not always bring in for a non-reactive project.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
class ReactiveTodoClientTest {
@Test
void getsTodo() {
WebClient webClient = WebClient.builder()
.baseUrl("http://localhost")
.exchangeFunction(request -> {
assertEquals("/todos/1", request.url().getPath());
return Mono.just(ClientResponse.create(HttpStatus.OK)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body("{\"id\":1,\"userId\":1,\"title\":\"write tests\",\"completed\":false}")
.build());
})
.build();
ReactiveTodoClient client = HttpServiceProxyFactory
.builderFor(WebClientAdapter.create(webClient))
.build()
.createClient(ReactiveTodoClient.class);
StepVerifier.create(client.getTodo(1))
.assertNext(todo -> assertEquals("write tests", todo.title()))
.verifyComplete();
}
}StepVerifier subscribes for you and fails the test if the Mono errors or never completes. Do not call .block() in tests just to read the value. It hides signal-level mistakes such as an unexpected extra element.
Choosing blocking or reactive
| Situation | Better fit |
|---|---|
| Servlet application with thread-per-request code | `RestClient` |
| WebFlux application, or code that fans out many calls in parallel | `WebClient` |
| Streaming a large response or server-sent events | `WebClient` with `Flux` |
| Mixed application that needs both | Two interfaces and two adapters, or a `WebClient` interface with blocking methods |
Switching to WebClient only to run concurrent calls in a servlet application is a reasonable use. Switching so the code looks reactive is not. A reactive client that is blocked immediately gives you the complexity without the benefit.
Exercise
A teammate writes todoClient.delete(42); for a Mono<Void> delete(long id) method on a WebClientAdapter-backed client, and reports that the todo is never deleted and no error appears. What is wrong, and what are two ways to fix it?
Show answer
The method returns a Mono<Void>, which is lazy. Calling it only builds the request description, and no HTTP request is sent until something subscribes. Fix it either by subscribing, for example todoClient.delete(42).subscribe(), or by returning the Mono from the method so the framework or caller subscribes (for example from a WebFlux controller). In a blocking context at the edge of the application, .block() also works, but never inside a reactive chain.
Exercise
A Mono<Todo> call returns 404, and the code wraps todoClient.getTodo(99) in try { ... } catch (WebClientResponseException.NotFound e). The catch block never runs. Why, and how should the 404 be handled?
Show answer
The call returns a Mono without sending anything, so no exception is thrown at that point. The NotFound exception is delivered later as an error signal to subscribers. Handle it in the pipeline, for example todoClient.getTodo(99).onErrorResume(WebClientResponseException.NotFound.class, e -> Mono.empty()).