@Slf4j
public class DConfig4Object1 {
protected static Logger logger = LoggerFactory.getLogger(DConfig4Object1.class);
public static void main(String[] args) throws InterruptedException {
LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
.initialCapacity(10)
.maximumSize(10)
.expireAfterWrite(3, TimeUnit.SECONDS)
.removalListener(notification -> {
logger.info(notification.getKey() + " " + notification.getValue() + " 被移除,原因:" + notification.getCause());
}).build(new CacheLoader<String, Integer>() {
//数据加载,默认返回-1,也可以是查询操作,如从DB查询
@Override
public Integer load(String key) throws Exception {
return -1;
}
});
//插入十个数据
for(int i=0; i<13; i++){
cache.put("key"+i, i);
}
//超过最大容量的,删除最早插入的数据,size正确
System.out.println("size :" + cache.size()); //10
cache.invalidate("key12");
Thread.sleep(5000);
System.out.println("size :" + cache.size()); //10
}
}
运行结果:
DConfig4Object1 - key0 0 被移除,原因:SIZE
DConfig4Object1 - key1 1 被移除,原因:SIZE
DConfig4Object1 - key2 2 被移除,原因:SIZE
size :10
DConfig4Object1 - key12 12 被移除,原因:EXPLICIT
size :9
手动删除和超过最大容量都会触发removalListener事件
@Slf4j
public class DConfig4Object1 {
protected static Logger logger = LoggerFactory.getLogger(DConfig4Object1.class);
public static void main(String[] args) throws InterruptedException, ExecutionException {
LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
.initialCapacity(10)
.maximumSize(10)
.expireAfterWrite(1, TimeUnit.SECONDS)
.removalListener(notification -> {
logger.info(notification.getKey() + " " + notification.getValue() + " 被移除,原因:" + notification.getCause());
}).build(new CacheLoader<String, Integer>() {
//数据加载,默认返回-1,也可以是查询操作,如从DB查询
@Override
public Integer load(String key) throws Exception {
if (key.equals("key0")) {
return 1000;
} else if (key.equals("key1")) {
return 1001;
} else if (key.equals("key2")) {
return 1002;
} else if (key.equals("key3")) {
return 1003;
} else if(key.equals("key4")) {
return 1004;
} else if(key.equals("key5")) {
return 1005;
} else if (key.equals("key6")) {
return 1006;
}
return 2000;
}
});
//插入十三个数据
for(int i=0; i<2; i++){
cache.put("key"+i, i);
}
System.out.println("size :" + cache.size()); //13
//cache.invalidate("key12");
Thread.sleep(5000);
System.out.println();
for(int i=0; i<2; i++){
Integer value = cache.get("key"+i);
System.out.println("key"+i + ", value = " + value);
}
System.out.println("size :" + cache.size()); //13
}
}
运行结果:
size :2
DConfig4Object1 - key0 0 被移除,原因:EXPIRED
DConfig4Object1 - key1 1 被移除,原因:EXPIRED
key0, value = 1000
key1, value = 1001
size :2