I need to consume a reactive rest API (built with spring webflux) on a backend job (executable jar).
I've read about Spring WebClient, but I am not understanding some points.
For instance:
WebClient webClient = WebClient.create("http://localhost:8080");
Mono<Person> person = webClient.get()
.uri("/persons/{id}", 42)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.then(response -> response.bodyToMono(Person.class));
On the last line, there is a "bodyToMono". So that's my question:
If the Rest API being called is already a reactive service, do I need to transform the response to a mono? Is there some point I'm missing?
From my perspective, I think could have a way to let explicit in the code that my Rest API is reactive, but probably is something I am not aware about.
Spring Reactive Web: The spring reactive web provides a reactive feature to our application. Spring Data R2DBC: Provides Reactive Relational Database Connectivity to persist data in SQL stores using Spring Data in reactive applications. Lombok: Java annotation library which helps to reduce boilerplate code.
What Is Spring WebClient? The Spring WebClient is a reactive HTTP library; it's the follow-up to the Spring RestTemplate which is now in maintenance mode. Also, whereas the RestTemplate was a synchronous blocking library, WebClient is an asynchronous non-blocking library.
WebClient is a non-blocking, reactive client for performing HTTP requests with Reactive Streams back pressure.
Yes it is required. The whole idea of being reactive is to make sure none of the Thread are blocked for IO.
You may have made your server side service reactive, but when your consuming that what is the benefit you get when your client is blocked untill there is a response from server. Your client thread keeps waiting untill the server responds. Which is not desired.
webClient.get()
.uri("/persons/{id}", 42)
.accept(MediaType.APPLICATION_JSON)
.exchange().block()
will block your current client thread to wait till the server responds. This can block your client thread.
webClient.get()
.uri("/persons/{id}", 42)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.then(response -> response.bodyToMono(Person.class));
Gives you a Mono which is a reference to a publisher that can emit a single value in future. So the client thread is non blocked.
I have blogged explaining this more. https://dzone.com/articles/spring-5-reactive-web-services
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