Spring WebClient: How to stream large byte[] to file?

后端 未结 4 936
天命终不由人
天命终不由人 2021-02-02 17:11

It seems like it the Spring RestTemplate isn\'t able to stream a response directly to file without buffering it all in memory. What is the proper to achieve this us

4条回答
  •  难免孤独
    2021-02-02 17:40

    I cannot test whether or not the following code effectively does not buffer the contents of webClient payload in memory. Nevertheless, i think you should start from there:

    public Mono testWebClientStreaming() throws IOException {
        Flux stream = 
                webClient
                        .get().accept(MediaType.APPLICATION_OCTET_STREAM)
                        .retrieve()
                .bodyToFlux(DataBuffer.class);
        Path filePath = Paths.get("filename");
        AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(filePath, WRITE);
        return DataBufferUtils.write(stream, asynchronousFileChannel)
                .doOnNext(DataBufferUtils.releaseConsumer())
                .doAfterTerminate(() -> {
                    try {
                        asynchronousFileChannel.close();
                    } catch (IOException ignored) { }
                }).then();
    }
    

提交回复
热议问题