Guava-Cache内存缓存API使用

guava-cache内存缓存API使用java

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次,其余则命中。ide

guava的内存缓存很是强大,能够设置各类选项,并且很轻量,使用方便。另外还提供了下面一些方法,来方便各类须要:函数

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