Sub topic 13
Reactive clients with WebClient
This chapter assumes you have read the earlier chapters on @HttpExchange, HttpServiceProxyFactory, and bean registration. It also assumes 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.
Same interface, different adapter
The interface you write does not change. What changes is the adapter passed to HttpServiceProxyFactory. RestClientAdapter runs requests on the calling thread. WebClientAdapter wraps a WebClient, which is non-blocking, so the proxy can return reactive types.
Add spring-boot-starter-webflux to your project. Spring Boot then auto-configures a WebClient.Builder, just as it does for RestClient.Builder.
Declaring reactive methods
Use Mono for a single value and Flux for a stream of values. Annotations and argument binding work as before.
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.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);
}Todo is the record from the earlier chapters. The same return-type rules apply. Mono<Void> replaces void, and Mono<ResponseEntity<T>> gives you status and headers along with the body.
Building the proxy
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();
return HttpServiceProxyFactory
.builderFor(WebClientAdapter.create(webClient))
.build()
.createClient(ReactiveTodoClient.class);
}
}The structure matches the RestClient version. Only the adapter and the builder type differ.
Nothing happens until you subscribe
A Mono or Flux returned by the proxy is a description of a request. The HTTP call starts when something subscribes. If you call getTodo(1) and ignore the result, no request is sent. In a WebFlux controller, return the publisher and the framework subscribes for you. In other code, compose it with operators such as map and flatMap.
Errors arrive as signals
A 4xx or 5xx response is not thrown at the call site. It is delivered as an error signal on the publisher. The exception types are WebClientResponseException and its subclasses, not the HttpClientErrorException family used by RestClient.
Mono<Todo> todo = client.getTodo(999)
.onErrorResume(WebClientResponseException.NotFound.class, e -> Mono.empty());A try/catch around the call would not catch this. The error appears only when the pipeline runs.
Mixing blocking and reactive
WebClientAdapter also accepts blocking return types such as Todo or List<Todo>. In that case the proxy blocks the calling thread until the response arrives. This is convenient in a servlet application that is gradually adopting reactive code. Never do it on a Reactor event-loop thread, because it can stall the whole application.
The reverse does not work. RestClientAdapter supports only blocking return types, so a Mono<Todo> method will fail with it.
Testing
MockRestServiceServer works only with RestClient and RestTemplate. For a WebClient-based client, use one of these options:
- Start
MockWebServerfrom OkHttp, point the base URL at it, and queue canned responses. - Provide a custom
ExchangeFunctionto theWebClient.Builderthat returns fixed responses. - Use
StepVerifierfromreactor-testto assert on the returned publisher.
Choosing between them
| Situation | Adapter |
|---|---|
| Servlet app, blocking code | `RestClientAdapter` |
| WebFlux app, or you need `Flux` streaming | `WebClientAdapter` |
| Servlet app that needs a few reactive calls | `WebClientAdapter`, with care |
Exercise
A teammate writes try { client.getTodo(999); } catch (WebClientResponseException.NotFound e) { ... } against a Mono<Todo> method, and the catch block never runs. Why, and how do you fix it?
Show answer
The method returns a Mono, so no request is sent and no error is thrown at the call site. The error is emitted as a signal when the Mono is subscribed. Handle it in the pipeline, for example with onErrorResume(WebClientResponseException.NotFound.class, e -> Mono.empty()), and make sure something subscribes to the result.