How to use Reactive API Spring Rest with WebClient

I need to use the reactive rest API (built with spring webflux) on a backend job (jar executable).

I read about spring WebClient but I don't understand some points.

For example:

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));

      

The last line contains "bodyToMono". So my question is:

If the Rest API being called is already a reactive service, do I need to convert the response to mono? Is there a point I am missing?

From my point of view, I think I would have a way to make it explicit in code that my Rest API is reactive, but this is probably something I don't know about.

+3


source to share


1 answer


Yes, it is necessary. The whole idea behind react is to make sure that none of the threads are blocked for I / O.

You might have made your server side service reactive, but when you consume what you get when your client is blocked until there is a response from the server. Your client thread keeps waiting until the server responds. Which is undesirable.

webClient.get()
        .uri("/persons/{id}", 42)
        .accept(MediaType.APPLICATION_JSON)
        .exchange().block()

      

will block the current client thread to wait for a server response. This can block your client thread.



webClient.get()
        .uri("/persons/{id}", 42)
        .accept(MediaType.APPLICATION_JSON)
        .exchange()
        .then(response -> response.bodyToMono(Person.class));

      

Provides you with mono, which is a link to a publisher that may emit one value in the future. This way the client thread is not blocked.

I have a blog explaining this more. https://dzone.com/articles/spring-5-reactive-web-services

+5


source







All Articles