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

后端 未结 4 997
天命终不由人
天命终不由人 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:17

    Store the body to a temporary file and consume

    static  Mono writeBodyToTempFileAndApply(
            final WebClient.ResponseSpec spec,
            final Function function) {
        return using(
                () -> createTempFile(null, null),
                t -> write(spec.bodyToFlux(DataBuffer.class), t)
                        .thenReturn(function.apply(t)),
                t -> {
                    try {
                        deleteIfExists(t);
                    } catch (final IOException ioe) {
                        throw new RuntimeException(ioe);
                    }
                }
        );
    }
    

    Pipe the body and consume

    static  Mono pipeBodyAndApply(
            final WebClient.ResponseSpec spec, final ExecutorService executor,
            final Function function) {
        return using(
                Pipe::open,
                p -> {
                    final Future future = executor.submit(
                            () -> write(spec.bodyToFlux(DataBuffer.class), p.sink())
                                    .log()
                                    .doFinally(s -> {
                                        try {
                                            p.sink().close();
                                            log.debug("p.sink closed");
                                        } catch (final IOException ioe) {
                                            throw new RuntimeException(ioe);
                                        }
                                    })
                                    .subscribe(DataBufferUtils.releaseConsumer())
                    );
                    return just(function.apply(p.source()))
                            .log()
                            .doFinally(s -> {
                                try {
                                    final Disposable disposable = future.get();
                                    assert disposable.isDisposed();
                                } catch (InterruptedException | ExecutionException e) {
                                    e.printStackTrace();
                                }
                            });
                },
                p -> {
                    try {
                        p.source().close();
                        log.debug("p.source closed");
                    } catch (final IOException ioe) {
                        throw new RuntimeException(ioe);
                    }
                }
        );
    }
    

提交回复
热议问题