Spring Webflux migrate WebClient.exchange() to WebClient.exchangeToMono() with DataBuffer
Asked Answered
P

0

6

While upgrading one project to spring webflux 5.3.3 I noticed that the Webclient.exchange method was getting deprecated (link).

I already read the question Spring WebFlux 5.3.0 - WebClient.exchangeToMono() and I have a question regarding using DataBuffer and how to use them within .exchangeToMono().

So far I understood it the new methods WebClient.exchangeToMono() and .exchangeToFlux() are enforcing that developers should take care of the request body within because the next step of spring webflux is to release the entire response body.

Just to make my basic question more visible, let's imagine we want to create a proxy that should pass everything to the caller. This could look like:

.exchangeToMono { clientResp ->
   val statusCode = clientResponse.statusCode()
   val respHeaders = clientResponse.headers().asHttpHeaders()
   val body = clientResponse.body(BodyExtractors.toDataBuffers())
      .doOnEach {
         if (it.isOnComplete || it.isOnError) {
            it.get()?.let { buffer ->
               DataBufferUtils.release(buffer)
            }
         }
      }
   ServerResponse.status(statusCode)
      .headers { headers -> headers.addAll(respHeaders) }
      .body(BodyInserters.fromDataBuffers(body))
}

However this code snippet wouldn't work because the body would only be read if someone would subscribe the whole chain but immediately after the .exchangeToMono() method the response body would be released caused by .releaseIfNotConsumed() which leads to response.releaseBody() which calls body(BodyExtractors.toDataBuffers()).map(DataBufferUtils::release).

So my question is how would such an example look like if we don't want to load the complete response body into the memory. Can someone please point me in the right direction?

Pokeberry answered 29/1, 2021 at 13:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.