【发布时间】:2018-10-09 23:47:40
【问题描述】:
在 Project Reactor 中下载完成后,我无法正确保存文件。
class HttpImageClientDownloader implements ImageClientDownloader {
private final ExchangeFunction exchangeFunction;
HttpImageClientDownloader() {
this.exchangeFunction = ExchangeFunctions.create(new ReactorClientHttpConnector());
}
@Override
public Mono<File> downloadImage(String url, Path destination) {
ClientRequest clientRequest = ClientRequest.create(HttpMethod.GET, URI.create(url)).build();
return exchangeFunction.exchange(clientRequest)
.map(clientResponse -> clientResponse.body(BodyExtractors.toDataBuffers()))
//.flatMapMany(clientResponse -> clientResponse.body(BodyExtractors.toDataBuffers()))
.flatMap(dataBuffer -> {
AsynchronousFileChannel fileChannel = createFile(destination);
return DataBufferUtils
.write(dataBuffer, fileChannel, 0)
.publishOn(Schedulers.elastic())
.doOnNext(DataBufferUtils::release)
.then(Mono.just(destination.toFile()));
});
}
private AsynchronousFileChannel createFile(Path path) {
try {
return AsynchronousFileChannel.open(path, StandardOpenOption.CREATE);
} catch (Exception e) {
throw new ImageDownloadException("Error while creating file: " + path, e);
}
}
}
所以我的问题是: DataBufferUtils.write(dataBuffer, fileChannel, 0) 是否阻塞?
磁盘慢的时候怎么办?
关于 ImageDownloadException 发生时会发生什么的第二个问题, 在 doOnNext 中我想释放给定的数据缓冲区,是这种操作的好地方吗?
我也觉得这行:
.map(clientResponse -> clientResponse.body(BodyExtractors.toDataBuffers()))
可能会阻塞...
【问题讨论】:
标签: spring-boot reactive-programming spring-webflux project-reactor