Igor Veloso
Igor Veloso

Reputation: 487

How to consume a Reactive Spring Rest API with WebClient

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.

Upvotes: 12

Views: 11398

Answers (1)

Praneeth Ramesh
Praneeth Ramesh

Reputation: 3554

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

Upvotes: 13

Related Questions