'Spring WebFlux Kotlin Coroutines Binary Stream

I'm writing a Rest API that proxies binary images. I'm trying to use the support recently added to Spring WebFlux for Kotlin coroutines. In a controller I'm making a request to another service which returns a binary image and then stream that image to the calling client, in the response body. I'm using DataBuffer, which I understood would not load the entire response from the other service in memory. But I'm getting the following error:

Exceeded limit on max bytes to buffer : 262144

I've read posts on here that describe how to increase the buffer size, but that begs the question, "does DataBuffer load the entire response body in memeory?"

The binary images I'm dealing with could be GBs in size.

Here's the code to my controller.

    @GetMapping("/test")
    internal suspend fun proxy(
        request: ServerHttpRequest,
        @RequestParam("forwardUrl")
        forwardUrl: String
    ): ResponseEntity<StreamingResponseBody> {

        val stream = client.get()
            .uri(forwardUrl)
            .awaitExchange()
            .awaitBody<DataBuffer>()

        val responseBody: StreamingResponseBody = StreamingResponseBody { outputStream: OutputStream ->
            Unit
            stream.asInputStream().transferTo(outputStream)
        }

        return ResponseEntity<StreamingResponseBody>(responseBody, HttpStatus.OK)
    }

What is the right way to achieve streaming the response body of a WebClient request to the response body of a request being handled by my controller, without loading the entire response body in memory?

Thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source