一、說明
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