Guava Cache简介

Guava Cache使用的几种方式

1、使用CacheLoader加载
public static void main(String[] args) {
// 缓存加载器
CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public String load(String s) throws Exception {
Thread.sleep(1000);
System.out.println(s + " loaded from cache loader.");
return s + "的值";
}
};
// 数据移除监听器
RemovalListener<String, String> listener = new RemovalListener<String, String>() {
@Override
public void onRemoval(RemovalNotification<String, String> removal) {
System.out.println(removal.getKey() + "=" + removal.getValue() + " was evicted...");
}
};
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
// 缓存容量为5
.maximumSize(5)
// 移除元素监听器
.removalListener(listener)
// 超时机制
.expireAfterWrite(10, TimeUnit.MINUTES)
.expireAfterAccess(10, TimeUnit.MINUTES)
// 设置缓存加载器
.build(loader);
for (int i = 0; i < 10; i++) {
cache.put("key"+i, "value"+i);
System.out.println("key"+i + "=" + "value"+i + "was put into cache");
}
// 获取元素,不存在则返回null
System.out.println(cache.getIfPresent("key"));
// 获取元素,不存在则通过cacheLoader.load()加载
try {
System.out.println(cache.get("key777"));
} catch (ExecutionException e) {
System.out.println("key 不存在");
}
}
2、使用Callable加载
public static void main(String[] args) {
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(5)
.build();
cache.put("key666", "value666");
// 不存在,则返回null
System.out.println(cache.getIfPresent("key333"));
try {
// 存在就返回,不存在则调用call()方法,将返回值缓存、返回
System.out.println(cache.get("key333", new Callable<String>() {
@Override
public String call() throws Exception {
return "运算、缓存、返回";
}
}));
} catch (ExecutionException e) {
e.printStackTrace();
}
}
Guava Cache回收策略


本文介绍了Guava Cache的基础知识,包括Guava Cache的简介,详细阐述了两种使用方式:通过CacheLoader和Callable进行加载,并探讨了Guava Cache的回收策略。

1174

被折叠的 条评论
为什么被折叠?



