有没有办法使用 Mono 从 WebClient 调用缓存响应?

问题描述 投票:0回答:1

如果输入相同,是否有办法缓存调用的响应?例如,如果文件名相同,我不想再次使用 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];
      });
}
java spring-webflux project-reactor spring-webclient publisher
1个回答
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));
}
© www.soinside.com 2019 - 2024. All rights reserved.