【问题标题】:Downloading file using Spring Webclient and AsynchronousFileChannel, file is empty使用 Spring Webclient 和 AsynchronousFileChannel 下载文件,文件为空
【发布时间】:2021-04-27 14:32:44
【问题描述】:

我想使用 Webflux 和 AsynchronousFileChannel 通过 URL 下载几张照片,所有文件都已创建但为空。

这是我的代码:

public void downloadFilesFromUrl() throws IOException {
    List<Photo> notDownloadedFiles = //get photos with name and URL;
    for (Photo photo : notDownloadedFiles) {
        Path path = Paths.get(pathToFiles + File.separator + photo.getPhotoName());
        WebClient client = WebClient.builder().baseUrl(photo.getLoadSource()).build();
        Flux<DataBuffer> dataBufferFlux = client
                .get().accept(MediaType.APPLICATION_OCTET_STREAM)
                .retrieve()
                .bodyToFlux(DataBuffer.class);
        saveFileOnComputer(path, dataBufferFlux);
    }
}

private void saveFileOnComputer(Path path, Flux<DataBuffer> dataBufferFlux) throws IOException {
    AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, CREATE, WRITE);
    DataBufferUtils.write(dataBufferFlux, asynchronousFileChannel)
            .doOnNext(DataBufferUtils.releaseConsumer())
            .doAfterTerminate(() -> {
                try {
                    asynchronousFileChannel.close();
                } catch (IOException ignored) { }
            }).then();
}

如果我尝试使用

DataBufferUtils.write(dataBufferFlux, path, StandardOpenOption.CREATE).block();

而不是调用 saveFileOnServer(..) 方法,一切都很好。但我想完全使用 AsynchronousFileChannel。

【问题讨论】:

    标签: java spring spring-boot spring-webflux spring-webclient


    【解决方案1】:

    好的,我想我修好了。

    private void saveFileOnServer(Path path, Flux<DataBuffer> dataBufferFlux) throws IOException {
        AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, CREATE, WRITE);
        DataBufferUtils.write(dataBufferFlux, asynchronousFileChannel).subscribe();
    }
    

    官方documentation说“注意,在返回的Flux被订阅之前,写入过程不会开始”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2021-02-09
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      • 2015-12-30
      相关资源
      最近更新 更多