Downlolad and save file from ClientRequest using ExchangeFunction in Project Reactor

前端 未结 1 1041
野趣味
野趣味 2021-01-14 03:00

I have problem with correctly saving a file after its download is complete in Project Reactor.

class HttpImageClientDownloader implements ImageClientDownload         


        
相关标签:
1条回答
  • 2021-01-14 03:19

    Here's another (shorter) way to achieve that:

    Flux<DataBuffer> data = this.webClient.get()
            .uri("/greeting")
            .retrieve()
            .bodyToFlux(DataBuffer.class);
    
    Path file = Files.createTempFile("spring", null);
    WritableByteChannel channel = Files.newByteChannel(file, StandardOpenOption.WRITE);
    Mono<File> result = DataBufferUtils.write(data, channel)
            .map(DataBufferUtils::release)
            .then(Mono.just(file));
    

    Now DataBufferUtils::write operations are not blocking because they use non-blocking IO with channels. Writing to such channels means it'll write whatever it can to the output buffer (i.e. may write all the DataBuffer or just part of it).

    Using Flux::map or Flux::doOnNext is the right place to do that. But you're right, if an error occurs, you're still responsible for releasing the current buffer (and all the remaining ones). There might be something we can improve here in Spring Framework, please keep an eye on SPR-16782.

    I don't see how your last sample shows anything blocking: all methods return reactive types and none are doing blocking I/O.

    0 讨论(0)
提交回复
热议问题