直接上干货
相关原理可以看官方文档
private static final Logger log = LoggerFactory.getLogger(CacheMap.class);
/**
* @desction:
*/
private static Cache<String,Object> cache;
static {
cache = CacheBuilder.newBuilder().maximumSize(10000)
.expireAfterWrite(2, TimeUnit.SECONDS)
.initialCapacity(10)
.removalListener(new RemovalListener<String, Object>() {
public void onRemoval(RemovalNotification<String, Object> rn) {
if(log.isInfoEnabled()){
log.info("被移除缓存{}:{}",rn.getKey(),rn.getValue());
}
}
}).build();
}
/**
* @desction: 获取缓存
* @author: wangji
* @date: 2017/11/22 9:50
*/
public static Object get(String key){
return StringUtils.isNotEmpty(key)?cache.getIfPresent(key):null;
}
/**
* @desction: 放入缓存
* @author: wangji
* @date: 2017/11/22 9:50
*/
public static void put(String key,Object value){
if(StringUtils.isNotEmpty(key) && value !=null){
cache.put(key,value);
}
}
/**
* @desction: 移除缓存
* @author: wangji
* @date: 2017/11/22 9:50
*/
public static void remove(String key){
if(StringUtils.isNotEmpty(key)){
cache.invalidate(key);
}
}
/**
* @desction: 批量删除缓存
* @author: wangji
* @date: 2017/11/22 9:49
*/
public static void remove(List<String> keys){
if(keys !=null && keys.size() >0){
cache.invalidateAll(keys);
}
}
以下为测试类
public class CaCheMapTest {
private static final String KEY ="key_test";
private static final Map map = new HashMap<String,String>();
private static final List<String> list = new ArrayList<>();
static{
map.put("1","1");
list.add("test1");
list.add("test2");
list.add("test3");
}
/**
* 存储本地缓存测试,添加数据
*/
public void addCache() throws InterruptedException {
CacheMap.put(KEY,list);
System.out.println("添加缓存成功");
Object o = CacheMap.get(KEY);
System.out.println("获取缓存数据:"+o);
//休眠4秒
TimeUnit.SECONDS.sleep(4);
//再获取数据,此时数据已经过期
Object o1 = CacheMap.get(KEY);
System.out.println("第二次获取缓存数据:"+o1);
}