1. 根据时间过期
第一步:引入maven依赖
<dependency>
<groupId>net.jodah</groupId>
<artifactId>expiringmap</artifactId>
<version>0.5.9</version>
</dependency>
第二步:实现代码
private ExpiringMap<String, AtomicLong> expiringCache = ExpiringMap.builder().expirationPolicy(ExpirationPolicy.ACCESSED)
// .variableExpiration()
// 同步过期提醒
// .expirationListener((key, value) -> remindExpiration(key, value))
// 异步过期提醒
.asyncExpirationListener((key, value) -> expireRollback(key, value))
.expiration(10,TimeUnit.SECONDS).build();
public void putValue(String key, long value) {
AtomicLong atomicLong = expiringCache.get(key);
if (Objects.isNull(atomicLong)) {
atomicLong = new AtomicLong(0L);
}
atomicLong.addAndGet(value);
expiringCache.put(key, atomicLong);
}
public Long getValue(String key) {
AtomicLong atomicLong = expiringCache.get(key);
if (Objects.isNull(atomicLong)) {
return -1L;
} else {
return atomicLong.get();
}
}
private void expireRollback(Object key, Object value) {
log.info(String.format("key: %s 过期了", key));
}
}