11
votes

What is the proper way to make an api call via springs WebClient, but ignore the result? The ClientResponse object specifically calls out that I have to do something with the result...

Docs:

NOTE: When given access to a ClientResponse, through the WebClient exchange() method, you must always use one of the body or toEntity methods to ensure resources are released and avoid potential issues with HTTP connection pooling. You can use bodyToMono(Void.class) if no response content is expected. However keep in mind that if the response does have content, the connection will be closed and will not be placed back in the pool.

Can I make a WebClient call and ignore the results? or is there a generic catch all "body or toEntity method" that I can use and then ignore?

1

1 Answers

21
votes

Prior to Spring Framework 5.2, using the WebClient#exchange() method and dealing directly with the Mono<ClientResponse> could be quite complex or lead to potential memory leaks.

As of Spring Framework 5.2, this has been made much easier for developers and the exchange() method has been deprecated.

Mono<ResponseEntity<Void>> response = webClient.put()
     .uri("https://example.org/book/123")
     .retrieve()
     .toBodilessEntity();

Spring will read the response body (if present) and release the data buffers, and then return the connection to the pool. It's making sure that there's no memory leak, including when additional Reactor operators are used.