Guava Cache源码

时间:2020-04-25
本文章向大家介绍Guava Cache源码,主要包括Guava Cache源码使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Guava Cache源码简析

缓存的使用场景:在计算或者检索一个值得代价很高,并对同样的输入需要不止一次获取对应值得时候,就可以考虑缓存。

创建Cache缓存对象LoadingCache:

 1 loadingCache = CacheBuilder.newBuilder()
 2                 .expireAfterWrite(2, TimeUnit.SECONDS)
 3                 //表示声明一个监听器,在移除缓存的时候可以做些额外的操作
 4                 .removalListener(new RemovalListener<Object, Object>() {
 5                     @Override
 6                     public void onRemoval(RemovalNotification<Object, Object> notification) {
 7                         LOGGER.info("删除原因={},删除 key={},删除 value={}", notification.getCause(), notification.getKey(), notification.getValue());
 8                     }
 9                 })
10                 //下面是指定缓存加载值的方法
11                 .build(new CacheLoader<Integer, AtomicLong>() {
12                     @Override
13                     public AtomicLong load(Integer key) throws Exception {
14                         return new AtomicLong(0);
15                     }
16                 });

原文地址:https://www.cnblogs.com/seedss/p/12774478.html