轉載:http://outofmemory.cn/java/guava/cache/how-to-use-guava-cache
http://www.cnblogs.com/parryyang/p/5777019.html
https://yq.aliyun.com/articles/46900 //源碼解析
作為Google的core libraries,直接提供Cache實現,足以證明Cache應用的廣泛程度。 然而作為工具庫中的一部分,我們自然不能期待Guava對Cache有比較完善的實現。因而Guava中的Cache只能用於一些把Cache作為一種輔助設計的項目或者在項目的前期為了實現簡單而引入。
Guava Cache有兩種創建方式:
1. cacheLoader
2. callable callback
通過這兩種方法創建的cache,和通常用map來緩存的做法比,不同在於,這兩種方法都實現了一種邏輯——從緩存中取key X的值,如果該值已經緩存過了,則返回緩存中的值,如果沒有緩存過,可以通過某個方法來獲取這個值。但不同的在於cacheloader的定義比較寬泛,是針對整個cache定義的,可以認為是統一的根據key值load value的方法。而callable的方式較為靈活,允許你在get的時候指定。
cacheLoader方式實現實例:
public static void main(String[] args) throws ExecutionException, InterruptedException{ //緩存接口這里是LoadingCache,LoadingCache在緩存項不存在時可以自動加載緩存 LoadingCache<Integer,Student> studentCache //CacheBuilder的構造函數是私有的,只能通過其靜態方法newBuilder()來獲得CacheBuilder的實例 = CacheBuilder.newBuilder() //設置並發級別為8,並發級別是指可以同時寫緩存的線程數
//refreshAfterWrite(3, TimeUnit.HOURS)// 給定時間內沒有被讀/寫訪問,則回收。 .concurrencyLevel(8) //設置寫緩存后8秒鍾過期 .expireAfterWrite(8, TimeUnit.SECONDS) //設置緩存容器的初始容量為10 .initialCapacity(10) //設置緩存最大容量為100,超過100之后就會按照LRU最近雖少使用算法來移除緩存項 .maximumSize(100) //設置要統計緩存的命中率 .recordStats() //設置緩存的移除通知 .removalListener(new RemovalListener<Object, Object>() { @Override public void onRemoval(RemovalNotification<Object, Object> notification) { System.out.println(notification.getKey() + " was removed, cause is " + notification.getCause()); } }) //build方法中可以指定CacheLoader,在緩存不存在時通過CacheLoader的實現自動加載緩存
///** 當本地緩存命沒有中時,調用load方法獲取結果並將結果緩存 **/ .build( new CacheLoader<Integer, Student>() { @Override public Student load(Integer key) throws Exception { System.out.println("load student " + key); Student student = new Student(); student.setId(key); student.setName("name " + key); return student; } } ); for (int i=0;i<20;i++) { //從緩存中得到數據,由於我們沒有設置過緩存,所以需要通過CacheLoader加載緩存數據 Student student = studentCache.get