一、说明
1、问题描述
在做项目中,通常会遇到这两种问题:
(1)、当hashMap存入的数据无更新时,却不能自动像redis那样自动老化数据;
(2)、当删除hashMap中的某个key时,想做一些额外处理工作;
这两个问题,谷歌的Cache<key,value>类型可以完美解决!
2、需要导入的pom
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
二、自动老化
1、代码
package com.cn.service;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
public class CacheBuilderSer {
public static void main(String[] args) {
//10秒钟之内存入的数据无更新,将会自动老化
Cache<String, Integer> cache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).build();
cache.put("1", 11);
cache.put("2", 22);
try {
Thread.sleep(1000*12);
cache.put("3", 33);
cache.put("4", 44);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 手动清除,相当于hashMap的Remove
cache.invalidate(1);
//cache.getIfPresent("3")相当于hashMap的get(key);
//System.out.println(cache.getIfPresent("1"));
System.out.println(cache.getIfPresent("1")+"//"+cache.getIfPresent("2")+"//"+cache.getIfPresent("3")+"//"+cache.getIfPresent("4"));
}
}
2、打印
null//null//33//44
三、删除并启动任务
1、代码
package com.cn.service;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
public class CacheBuilderService {
// 创建一个监听器
/**
* 缓存被移除的时候,得到这个通知,并做一些额外处理工作,这个时候RemovalListener就派上用场
*/
private static class MyRemovalListener implements RemovalListener<String, Integer> {
public void onRemoval(RemovalNotification<String, Integer> notification) {
String tips = String.format("key=%s,value=%s,reason=%s", notification.getKey(), notification.getValue(), notification.getCause());
System.out.println(tips);
}
}
public static void main(String[] args) {
// 创建一个带有RemovalListener监听的缓存
Cache<String, Integer> cache = CacheBuilder.newBuilder().removalListener(new MyRemovalListener()).build();
cache.put("1", 11);
cache.put("3", 33);
cache.put("4",44);
cache.put("2", 22);
// 手动清除并调用监听器做一些事情,相当于hashMap的Remove
cache.invalidate("1");
cache.invalidate("3");
//System.out.println(cache.getIfPresent("1"));
System.out.println(cache.getIfPresent("1")+"//"+cache.getIfPresent("2")+"//"+cache.getIfPresent("3")+"//"+cache.getIfPresent("4")); // null
}
}
2、打印
key=1,value=11,reason=EXPLICIT
key=3,value=33,reason=EXPLICIT
null//22//null//44