Sorry if this was asked before, but I didn't find a matching question.
I have an application that performs api calls to other services. I'm thinking of using WebClient over RestTemplate as it's advised by Spring. I'm performing exclusively synchronous calls. I know WebClient is designed with reactive approach in mind, but in theory is it ok to use WebClient solely for blocking calls? I'm concerned by the fact that I have to call .block()
on each call to get the data. So my questions are:
- How safe is it to use
.block()
and is it ok in general to block threads in WebClient? - Is the mechanics behind blocking calls with WebClient similar to what RestTemplate does?
- Is there a possibility that the performance would be worse than in case I just use RestTemplate?
Thanks in advance!
CodePudding user response:
In our applications we are migrating from RestTemplate to WebClient without any issues, .block() works just fine
Response response = this.webClient
.post()
.uri(uri)
.body(fromValue)
.retrieve()
.bodyToMono(Response.class)
.timeout(Duration.ofMillis(timeoutMillis))
.block();
This is doing the same as RestTemplate does, it's sending the request in a synchronized way, and we have it working in PROD since a couple of months without any issues
CodePudding user response:
Answering your questions:
- Please don't do that. By doing it you are throwing all the benefits of Spring Webflux into the trash can. You are replicating the non-reactive stack behaviour.
- In practice yes. The thread will be blocked waiting for a response from the service you are calling.
- I would say it would be similar, but your code would be harder to read without any benefit from it.
The bottom line is: so that you take full advantage of the reactive stack of Spring Webflux you need to have a fully reactive code base. Even the infrastructure must support reactive behaviour, being the most simple example the Database.
Additionally, you are confusing asynchronous and reactive behaviour. Spring Webflux is reactive by nature which brings other benefits to the table (take a look at https://www.baeldung.com/spring-mvc-async-vs-webflux).