第一步:引入guava的maven依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1.1-jre</version>
</dependency>
第二步:编写具体实现
//异步监听
private RemovalListener<String, AtomicLong> removealListener = RemovalListeners.asynchronous(notification -> {
RemovalCause cause = notification.getCause();
String key = notification.getKey();
AtomicLong value = notification.getValue();
System.out.println("#######################%%%");
log.error("#########################");
switch (cause) {
case EXPIRED:
log.error("时间过期,数据KEY:{}", JSON.toJSON(key));
break;
case SIZE:
log.error("超出容量,数据KEY:{}", JSON.toJSON(key));
break;
case COLLECTED:
break;
default:
return;
}
}, Executors.newSingleThreadExecutor());
private Cache<String, AtomicLong> cache = CacheBuilder.newBuilder()
.expireAfterAccess(1, TimeUnit.DAYS)
.initialCapacity(3)
.maximumSize(7)
.removalListener(removealListener).build();
private ConcurrentMap<String, AtomicLong> cacheInfoMap = cache.asMap();
public void putValue(String key, long value) {
AtomicLong atomicLong = cacheInfoMap.get(key);
if (Objects.isNull(atomicLong)) {
atomicLong = new AtomicLong(0L);
}
atomicLong.addAndGet(value);
cacheInfoMap.put(key, atomicLong);
}
public Long getValue(String key) {
AtomicLong atomicLong = cacheInfoMap.get(key);
if (Objects.isNull(atomicLong)) {
return -1L;
} else {
return atomicLong.get();
}
}