并发场景下,缓存失效处理场景

并发场景下,缓存失效,需要从数据库或下游查询缓存中的数据。

若并发流量都请求到下游,导致下游压力较大,可通过如下方式进行处理:

import java.util.concurrent.*;

public class SingleFlight {
  private final ConcurrentMap<Object, CompletableFuture<?>> cache = new ConcurrentHashMap<>();

  public <V> V execute(Object key, Callable<V> callable) throws Exception {
      CompletableFuture<?> future = cache.computeIfAbsent(key, k -> CompletableFuture.supplyAsync(() -> {
          // 查询数据库或下游服务
          try {
              return callable.call();
          } catch (Exception e) {
              throw new RuntimeException(e);
          }
      }).whenComplete((v, e) -> cache.remove(key)));

      return (V) future.get();
  }
}

  https://github.com/phicode/philib/blob/master/src/main/java/ch/bind/philib/concurrent/SingleFlight.java

posted @ 2024-08-13 19:47  开坦克的舒克  阅读(19)  评论(0)    收藏  举报