使用Guava的Cache功能

原创
2016/03/07 18:11
阅读数 841

Guava是google下的一个java工具类的项目,官方网站:https://github.com/google/guava,其中集合工具,缓存工具和并发工具是比较常用的几个工具集。

使用方法是pom中引入对应的包

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>19.0</version>
</dependency>

以下是常用的使用方法,我们需要把一个员工的工号(Interge.class)和他的用户信息(User.class)缓存起来

LoadingCache<Integer, User> users = CacheBuilder.newBuilder()
        .maximumSize(1000)
        .expireAfterWrite(10, TimeUnit.MINUTES)
        .build(
            new CacheLoader<Integer, User>() {
                public User load(Integer empId) throws Exception {
                    return getUserByEmpId(empId);
                }
        });

User user=users.get(TEST_EMPID);

 其中load方法只有在缓存中没有对应的数据的时候被调用,其他的时候会从缓存中取到

其中load方法是会抛出Exception的,如果不抛出对应的Exception,则调用的时候也可以使用getUnchecked(K)

在调用的时候也可以使用getAll(Iterabale<? extends K>)的方式获取批量数据。

另外Guava的Cache也可以使用get(K,Callaleb<V>)的方法,如果有缓存则返回,否则运算缓存再返回

Cache<Integer, User> users= CacheBuilder.newBuilder()
        .maximumSize(1000)
        .build(); 

try {
    cache.get(TEST_EMPID, new Callable<Integer, User>() {
        @Override
        public User call() throws AnyException {
            return getUserByEmpId(empId);
        }
    });
} catch (ExecutionException e) {
    throw new OtherException(e.getCause());
}

Guava的缓存有3种,

1 基于容量回收,这个和设置的maximunSize有关

2 定时回收,这个和设置的expireAfterAccess,expiredAfterWrite有关

3 基于引用回收,这个和设置的weakKeys,weakValues和softValues有关。

CacheBuilder.weakKeys():使用弱引用存储键。当键没有其它(强或软)引用时,缓存项可以被垃圾回收。因为垃圾回收仅依赖恒等式(==),使用弱引用键的缓存用==而不是equals比较键。
CacheBuilder.weakValues():使用弱引用存储值。当值没有其它(强或软)引用时,缓存项可以被垃圾回收。因为垃圾回收仅依赖恒等式(==),使用弱引用值的缓存用==而不是equals比较值。
CacheBuilder.softValues():使用软引用存储值。软引用只有在响应内存需要时,才按照全局最近最少使用的顺序回收。考虑到使用软引用的性能影响,我们通常建议使用更有性能预测性的缓存大小限定(见上文,基于容量回收)。使用软引用值的缓存同样用==而不是equals比较值。

Guava支持设置一个移除监听器,当你移除一个缓存项的时候做对应的操作

RemovalListener<Key, DatabaseConnection> removalListener = new RemovalListener<Key, DatabaseConnection>() {
    public void onRemoval(RemovalNotification<Key, DatabaseConnection> removal) {
        DatabaseConnection conn = removal.getValue();
        conn.close(); // tear down properly
    }
};

参考文档:

http://ifeve.com/google-guava/

http://ifeve.com/google-guava-cachesexplained/


展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
6 收藏
1
分享
返回顶部
顶部