適用性
緩存在很多情況下非常實用。例如,計算或檢索一個值的代價很高,並且對同樣的輸入需要不止一次獲取值的時候,就應當考慮使用緩存。
Guava Cache與ConcurrentMap很相似,但也不完全一樣。最基本的區別是ConcurrentMap會一直保存所添加的元素,直到顯式的移除;Guava Cache為了限制內存的占用,通常都是設定為自動回收元素。在某些場景下,盡管LoadingCahe不回收元素,但是它還是很有用的,因為它會自動加載緩存。
Guava Cache適用場景:
- 你願意消耗一部分內存來提升速度;
- 你已經預料某些值會被多次調用;
- 緩存數據不會超過內存總量;
Guava Cache是一個全內存的本地緩存實現,它提供了線程安全的實現機制。整體上來說Guava cache 是本地緩存的不二之選,簡單易用,性能好。
創建方式
CacheLoader和Callable通過這兩種方法創建的cache,和通常用map來緩存的做法比,不同在於這兩種方法都實現了一種邏輯——從緩存中取key X的值,如果該值已經緩存過了,則返回緩存中的值,如果沒有緩存過,可以通過某個方法來獲取這個值。
但不同的在於cacheloader的定義比較寬泛, 是針對整個cache定義的,可以認為是統一的根據key值load value的方法。而callable的方式較為靈活,允許你在get的時候指定。
public class AppkeyInfoLocalCache { private static Logger log = Logger.getLogger(AppkeyInfoLocalCache.class); static LoadingCache<String, AppkeyInfoBasic> cache = CacheBuilder.newBuilder().refreshAfterWrite(3, TimeUnit.HOURS)// 給定時間內沒有被讀/寫訪問,則回收。 .expireAfterAccess(APIConstants.TOKEN_VALID_TIME, TimeUnit.HOURS)// 緩存過期時間和redis緩存時長一樣 .maximumSize(1000).// 設置緩存個數 build(new CacheLoader<String, AppkeyInfoBasic>() { @Override /** 當本地緩存命沒有中時,調用load方法獲取結果並將結果緩存 **/ public AppkeyInfoBasic load(String appKey) throws DaoException { return getAppkeyInfo(appKey); } /** 數據庫進行查詢 **/ private AppkeyInfoBasic getAppkeyInfo(String appKey) throws DaoException { log.info("method<getAppkeyInfo> get AppkeyInfo form DB appkey<" + appKey + ">"); return ((AppkeyInfoMapper) SpringContextHolder.getBean("appkeyInfoMapper")) .selectAppkeyInfoByAppKey(appKey); } }); public static AppkeyInfoBasic getAppkeyInfoByAppkey(String appKey) throws DaoException, ExecutionException { log.info("method<getAppkeyInfoByAppkey> appkey<" + appKey + ">"); return cache.get(appKey); } }
2、Callable
public void testcallableCache()throws Exception{ Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build(); String resultVal = cache.get("jerry", new Callable<String>() { public String call() { String strProValue="hello "+"jerry"+"!"; return strProValue; } }); System.out.println("jerry value : " + resultVal); resultVal = cache.get("peida", new Callable<String>() { public String call() { String strProValue="hello "+"peida"+"!"; return strProValue; } }); System.out.println("peida value : " + resultVal); }