Basic question: How does Spring Reactors WebClient achieve non blocking when compared to RestTemplate? Doesn't it have to block somewhere after it has dispatched the request to the external service (for example)? HTTP by nature is synchronous right? So the calling application has to wait for the response? How does the thread know the context to react upon the response from the service?
WebClient Non-Blocking Client. On the other side, WebClient uses an asynchronous, non-blocking solution provided by the Spring Reactive framework. While RestTemplate uses the caller thread for each event (HTTP call), WebClient will create something like a “task” for each event.
It's important to note that even though it is, in fact, a non-blocking client and it belongs to the spring-webflux library, the solution offers support for both synchronous and asynchronous operations, making it suitable also for applications running on a Servlet Stack.
Spring Webflux does not block a thread to handle each request, because no thread is kept waiting for something to be done (e.g. waiting for an answer from a database). As written in 1., it can be blocked while waiting for an answer from a database or from another service that is called via HTTP.
A non-blocking way would be via one of the overloaded subscribe() methods. In this example, we will use the subscribe(Consumer<? super T> consumer) to get the data from Mono asynchronously. With subscribe(), the current thread will not be blocked waiting for the Publisher to emit data.
There are several separate questions here.
In the case of WebClient
and project Reactor, the Netty event loop is used to queue/dispatch/process events. Each read/write operation is done is a non-blocking manner, meaning that no thread sits waiting for an I/O operation to complete. In this model, concurrency is not done through thread pools, but there's a small number of threads that process unit of work which should never block.
From a pure HTTP standpoint (i.e. if you were capturing the HTTP packets on the network), you'd see no big difference between a RestTemplate
and a WebClient
call. The HTTP transport itself doesn't support the backpressure concept. So the client still has to wait for the response - the difference here is that the application using that WebClient
won't waste resources on waiting for that operation to complete - it will use them to process other events.
For more information on that, please check out the reactive programming introduction in the Reactor reference documentation and this talk given by Rossen Stoyanchev that explains things well if you're used to the typical Servlet container model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With