使用SpringWebClient和asynchronousfilechannel下载文件,文件为空

o4hqfura  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(403)

我想用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(..)方法,一切正常。但我想使用完全异步的文件通道。

j2datikz

j2datikz1#

好吧,我想我修好了。

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

官方文件说“注意,在返回的通量被订阅之前,写作过程不会开始”。

相关问题