【发布时间】: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