如果输入相同,是否有办法缓存调用的响应?例如,如果文件名相同,我不想再次使用 webClient 发出请求,因为响应需要一段时间。
Flux.fromIterable(files).flatMap(
file -> {
Mono<String> extension = getExtension(file.getName());
});
public Mono<String> getExtension(String fileName) {
return webClient.get().uri(extensionUrl + "?file=" + fileName).retrieve()
.bodyToMono(String[].class)
.map(
extensions -> {
System.out.println("finished retrieving");
return extensions[0];
});
}
Reactor 不提供任何缓存层,但您可以使用任何现有库或普通的
Map
进行缓存,然后在调用之前检查现有值。然后戴上一张doOnNext
。
缓存原始的
Mono
本身可能不起作用,因为它取决于实际实现,并且在许多情况下,对其的新订阅将导致新的请求。
所以最简单的实现是:
private Map<String, String> cache = new ConcurrentHashMap();
public Mono<String> getExtension(String fileName) {
String existing = cache.get(fileName);
if (existing != null) {
return Mono.just(existing);
}
return webClient.get().uri(extensionUrl + "?file=" + fileName).retrieve()
.bodyToMono(String[].class)
.map(....)
.doOnNext(value -> cache.put(fileName, value));
}