Guava-Cache内存缓存API使用

guava-cache内存缓存API使用

google guava中有cache包,此包提供内存缓存功能。内存缓存需要考虑很多问题,包括并发问题,缓存失效机制,内存不够用时缓存释放,缓存的命中率,缓存的移除等等。 当然这些东西guava都考虑到了。

guava中使用缓存需要先声明一个CacheBuilder对象,并设置缓存的相关参数,然后调用其build方法获得一个Cache接口的实例。请看下面的代码和注释,注意在注释中指定了Cache的各个参数。

import com.google.common.cache.*;
import com.wentianxia.entity.User;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class GuavaCache {
public static void main(String[] args) throws ExecutionException, InterruptedException{
//缓存接口这里是LoadingCache,LoadingCache在缓存项不存在时可以自动加载缓存
LoadingCache<Integer,User> studentCache
//CacheBuilder的构造函数是私有的,只能通过其静态方法newBuilder()来获得CacheBuilder的实例
= CacheBuilder.newBuilder()
//设置并发级别为8,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(8)
//设置写缓存后8秒钟过期
.expireAfterWrite(5, TimeUnit.SECONDS)
//设置缓存容器的初始容量为10
.initialCapacity(10)
//设置缓存最大容量为100,超过100之后就会按照LRU最近虽少使用算法来移除缓存项
.maximumSize(100)
//设置要统计缓存的命中率
.recordStats()
//设置缓存的移除通知
.removalListener(notification -> System.out.println(notification.getKey() + " was removed, cause is " + notification.getCause()))
//build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
.build(
new CacheLoader<Integer, User>() {
@Override
public User load(Integer key) throws Exception {
System.out.println("load student " + key);
User student = new User();
student.setId(Long.valueOf(key));
student.setUsername("name " + key);
return student;
}
}
);
for (int i=0;i<20;i++) {
//从缓存中得到数据,由于我们没有设置过缓存,所以需要通过CacheLoader加载缓存数据
User student = studentCache.get(1);
System.out.println(student);
//休眠1秒
TimeUnit.SECONDS.sleep(1);
}
System.out.println("cache stats:");
//最后打印缓存的命中率等 情况
System.out.println(studentCache.stats().toString());
}
}

以上程序的输出如下:

load student 1
Student{id=1, name=name 1}
Student{id=1, name=name 1}
Student{id=1, name=name 1}
Student{id=1, name=name 1}
Student{id=1, name=name 1}
Student{id=1, name=name 1}
Student{id=1, name=name 1}
Student{id=1, name=name 1}
1 was removed, cause is EXPIRED
load student 1
......
Student{id=1, name=name 1}
Student{id=1, name=name 1}
Student{id=1, name=name 1}
Student{id=1, name=name 1}
cache stats:
CacheStats{hitCount=17, missCount=3, loadSuccessCount=3, loadExceptionCount=0, totalLoadTime=1348802, evictionCount=2}

看看到在20此循环中命中次数是17次,未命中3次,这是因为我们设定缓存的过期时间是写入后的8秒,所以20秒内会失效两次,另外第一次获取时缓存中也是没有值的,所以才会未命中3次,其他则命中。

guava的内存缓存非常强大,可以设置各种选项,而且很轻量,使用方便。另外还提供了下面一些方法,来方便各种需要:

  • ImmutableMap<K, V> getAllPresent(Iterable<?> keys) 一次获得多个键的缓存值
  • put和putAll方法向缓存中添加一个或者多个缓存项
  • invalidate 和 invalidateAll方法从缓存中移除缓存项
  • asMap()方法获得缓存数据的ConcurrentMap<K, V>快照
  • cleanUp()清空缓存
  • refresh(Key) 刷新缓存,即重新取缓存数据,更新缓存

转载于:https://my.oschina.net/u/1024107/blog/870450

Guava 是一个 Google 的基于java1.6的类库集合的扩展项目,包括 collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, 等等. 这些高质量的 API 可以使你的JAVa代码更加优雅,更加简洁,让你工作更加轻松愉悦。下面我们就开启优雅Java编程学习之旅!   项目相关信息:   官方首页:http://code.google.com/p/guava-libraries   官方下载:http://code.google.com/p/guava-libraries/downloads/list   官方文档:http://docs.guava-libraries.googlecode.com/git/javadoc http://www.ostools.net/apidocs/apidoc?api=guava   源码包的简单说明:   com.google.common.annotations:普通注解类型。   com.google.common.base:基本工具类库和接口。   com.google.common.cache缓存工具包,非常简单易用且功能强大的JVM内缓存。   com.google.common.collect:带泛型的集合接口扩展和实现,以及工具类,这里你会发现很多好玩的集合。   com.google.common.eventbus:发布订阅风格的事件总线。   com.google.common.hash: 哈希工具包。   com.google.common.io:I/O工具包。   com.google.common.math:原始算术类型和超大数的运算工具包。   com.google.common.net:网络工具包。   com.google.common.primitives:八种原始类型和无符号类型的静态工具包。   com.google.common.reflect:反射工具包。   com.google.common.util.concurrent:多线程工具包。   类库使用手册:   一. 基本工具类:让使用Java语言更令人愉悦。   1. 使用和避免 null:null 有语言歧义, 会产生令人费解的错误, 反正他总是让人不爽。很多 Guava 的工具类在遇到 null 时会直接拒绝或出错,而不是默默地接受他们。   2. 前提条件:更容易的对你的方法进行前提条件的测试。   3. 常见的对象方法: 简化了Object常用方法的实现, 如 hashCode() 和 toString()。   4. 排序: Guava 强大的 "fluent Comparator"比较器, 提供多关键字排序。   5. Throwable类: 简化了异常检查和错误传播。   二. 集合类:集合类库是 Guava 对 JDK 集合类的扩展, 这是 Guava 项目最完善和为人所知的部分。   1. Immutable collections(不变的集合): 防御性编程, 不可修改的集合,并且提高了效率。   2. New collection types(新集合类型):JDK collections 没有的一些集合类型,主要有:multisets,multimaps,tables, bidirectional maps等等   3. Powerful collection utilities(强大的集合工具类): java.util.Collections 中未包含的常用操作工具类   4. Extension utilities(扩展工具类): 给 Collection 对象添加一个装饰器? 实现迭代器? 我们可以更容易使用这些方法。   三. 缓存: 本地缓存,可以很方便的操作缓存对象,并且支持各种缓存失效行为模式。   四. Functional idioms(函数式): 简洁, Guava实现了Java的函数式编程,可以显著简化代码。   五. Concurrency(并发):强大,简单的抽象,让我们更容易实现简单正确的并发性代码。   1. ListenableFuture(可监听的Future): Futures,用于异步完成的回调。   2. Service: 控制事件的启动和关闭,为你管理复杂的状态逻辑。   六. Strings: 一个非常非常有用的字符串工具类: 提供 splitting,joining, padding
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值