Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to make an api call via springs `WebClient`, but ignore the result?

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?

like image 601
Mike Rylander Avatar asked Jul 12 '18 18:07

Mike Rylander


People also ask

What is WebClient spring?

In simple words, the Spring WebClient is a component that is used to make HTTP calls to other services. It is part of Spring's web reactive framework, helps building reactive and non-blocking applications. To make HTTP requests, you might have used Spring Rest Template, which was simple and always blocking web client.

What is WebClient Java?

WebClient is a non-blocking, reactive client for performing HTTP requests with Reactive Streams back pressure. WebClient provides a functional API that takes advantage of Java 8 Lambdas. By default, WebClient uses Reactor Netty as the HTTP client library. But others can be plugged in through a custom.


1 Answers

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.

like image 124
Brian Clozel Avatar answered Sep 21 '22 06:09

Brian Clozel