并发场景下,缓存失效,需要从数据库或下游查询缓存中的数据。
若并发流量都请求到下游,导致下游压力较大,可通过如下方式进行处理:
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
标签:缓存,java,cache,并发,场景,key From: https://www.cnblogs.com/javaXRG/p/18357595