Guava Cache用法介紹

Guava Cache是在內存中緩存數據,相比較於數據庫或redis存儲,訪問內存中的數據會更加高效。Guava官網介紹,下面的這幾種狀況能夠考慮使用Guava Cache:redis

  1. 願意消耗一些內存空間來提高速度。數據庫

  2. 預料到某些鍵會被屢次查詢。設計模式

  3. 緩存中存放的數據總量不會超出內存容量。緩存

因此,能夠將程序頻繁用到的少許數據存儲到Guava Cache中,以改善程序性能。下面對Guava Cache的用法進行詳細的介紹。多線程

構建緩存對象

接口Cache表明一塊緩存,它有以下方法:app

public interface Cache<K, V> {
    V get(K key, Callable<? extends V> valueLoader) throws ExecutionException;

    ImmutableMap<K, V> getAllPresent(Iterable<?> keys);

    void put(K key, V value);

    void putAll(Map<? extends K, ? extends V> m);

    void invalidate(Object key);

    void invalidateAll(Iterable<?> keys);

    void invalidateAll();

    long size();

    CacheStats stats();

    ConcurrentMap<K, V> asMap();

    void cleanUp();
}

能夠經過CacheBuilder類構建一個緩存對象,CacheBuilder類採用builder設計模式,它的每一個方法都返回CacheBuilder自己,直到build方法被調用。構建一個緩存對象代碼以下。ide

public class StudyGuavaCache {
    public static void main(String[] args) {
        Cache<String,String> cache = CacheBuilder.newBuilder().build();
        cache.put("word","Hello Guava Cache");
        System.out.println(cache.getIfPresent("word"));
    }
}

上面的代碼經過CacheBuilder.newBuilder().build()這句代碼建立了一個Cache緩存對象,並在緩存對象中存儲了key爲word,value爲Hello Guava Cache的一條記錄。能夠看到Cache很是相似於JDK中的Map,可是相比於Map,Guava Cache提供了不少更強大的功能。性能

設置最大存儲

Guava Cache能夠在構建緩存對象時指定緩存所可以存儲的最大記錄數量。當Cache中的記錄數量達到最大值後再調用put方法向其中添加對象,Guava會先從當前緩存的對象記錄中選擇一條刪除掉,騰出空間後再將新的對象存儲到Cache中。ui

public class StudyGuavaCache {
    public static void main(String[] args) {
        Cache<String,String> cache = CacheBuilder.newBuilder()
                .maximumSize(2)
                .build();
        cache.put("key1","value1");
        cache.put("key2","value2");
        cache.put("key3","value3");
        System.out.println("第一個值:" + cache.getIfPresent("key1"));
        System.out.println("第二個值:" + cache.getIfPresent("key2"));
        System.out.println("第三個值:" + cache.getIfPresent("key3"));
    }
}

上面代碼在構造緩存對象時,經過CacheBuilder類的maximumSize方法指定Cache最多能夠存儲兩個對象,而後調用Cache的put方法向其中添加了三個對象。程序執行結果以下圖所示,能夠看到第三條對象記錄的插入,致使了第一條對象記錄被刪除。
圖片描述spa

設置過時時間

在構建Cache對象時,能夠經過CacheBuilder類的expireAfterAccess和expireAfterWrite兩個方法爲緩存中的對象指定過時時間,過時的對象將會被緩存自動刪除。其中,expireAfterWrite方法指定對象被寫入到緩存後多久過時,expireAfterAccess指定對象多久沒有被訪問後過時。

public class StudyGuavaCache {
    public static void main(String[] args) throws InterruptedException {
        Cache<String,String> cache = CacheBuilder.newBuilder()
                .maximumSize(2)
                .expireAfterWrite(3,TimeUnit.SECONDS)
                .build();
        cache.put("key1","value1");
        int time = 1;
        while(true) {
            System.out.println("第" + time++ + "次取到key1的值爲:" + cache.getIfPresent("key1"));
            Thread.sleep(1000);
        }
    }
}

上面的代碼在構造Cache對象時,經過CacheBuilder的expireAfterWrite方法指定put到Cache中的對象在3秒後會過時。在Cache對象中存儲一條對象記錄後,每隔1秒讀取一次這條記錄。程序運行結果以下圖所示,能夠看到,前三秒能夠從Cache中獲取到對象,超過三秒後,對象從Cache中被自動刪除。
圖片描述

下面代碼是expireAfterAccess的例子。

public class StudyGuavaCache {
    public static void main(String[] args) throws InterruptedException {
        Cache<String,String> cache = CacheBuilder.newBuilder()
                .maximumSize(2)
                .expireAfterAccess(3,TimeUnit.SECONDS)
                .build();
        cache.put("key1","value1");
        int time = 1;
        while(true) {
            Thread.sleep(time*1000);
            System.out.println("睡眠" + time++ + "秒後取到key1的值爲:" + cache.getIfPresent("key1"));
        }
    }
}

經過CacheBuilder的expireAfterAccess方法指定Cache中存儲的對象若是超過3秒沒有被訪問就會過時。while中的代碼每sleep一段時間就會訪問一次Cache中存儲的對象key1,每次訪問key1以後下次sleep的時間會加長一秒。程序運行結果以下圖所示,從結果中能夠看出,當超過3秒沒有讀取key1對象以後,該對象會自動被Cache刪除。
圖片描述

也能夠同時用expireAfterAccess和expireAfterWrite方法指定過時時間,這時只要對象知足二者中的一個條件就會被自動過時刪除。

弱引用

能夠經過weakKeys和weakValues方法指定Cache只保存對緩存記錄key和value的弱引用。這樣當沒有其餘強引用指向key和value時,key和value對象就會被垃圾回收器回收。

public class StudyGuavaCache {
    public static void main(String[] args) throws InterruptedException {
        Cache<String,Object> cache = CacheBuilder.newBuilder()
                .maximumSize(2)
                .weakValues()
                .build();
        Object value = new Object();
        cache.put("key1",value);

        value = new Object();//原對象再也不有強引用
        System.gc();
        System.out.println(cache.getIfPresent("key1"));
    }
}

上面代碼的打印結果是null。構建Cache時經過weakValues方法指定Cache只保存記錄值的一個弱引用。當給value引用賦值一個新的對象以後,就再也不有任何一個強引用指向原對象。System.gc()觸發垃圾回收後,原對象就被清除了。

顯示清除

能夠調用Cache的invalidateAll或invalidate方法顯示刪除Cache中的記錄。invalidate方法一次只能刪除Cache中一個記錄,接收的參數是要刪除記錄的key。invalidateAll方法能夠批量刪除Cache中的記錄,當沒有傳任何參數時,invalidateAll方法將清除Cache中的所有記錄。invalidateAll也能夠接收一個Iterable類型的參數,參數中包含要刪除記錄的全部key值。下面代碼對此作了示例。

public class StudyGuavaCache {
    public static void main(String[] args) throws InterruptedException {
        Cache<String,String> cache = CacheBuilder.newBuilder().build();
        Object value = new Object();
        cache.put("key1","value1");
        cache.put("key2","value2");
        cache.put("key3","value3");

        List<String> list = new ArrayList<String>();
        list.add("key1");
        list.add("key2");

        cache.invalidateAll(list);//批量清除list中所有key對應的記錄
        System.out.println(cache.getIfPresent("key1"));
        System.out.println(cache.getIfPresent("key2"));
        System.out.println(cache.getIfPresent("key3"));
    }
}

代碼中構造了一個集合list用於保存要刪除記錄的key值,而後調用invalidateAll方法批量刪除key1和key2對應的記錄,只剩下key3對應的記錄沒有被刪除。

移除監聽器

能夠爲Cache對象添加一個移除監聽器,這樣當有記錄被刪除時能夠感知到這個事件。

public class StudyGuavaCache {
    public static void main(String[] args) throws InterruptedException {
        RemovalListener<String, String> listener = new RemovalListener<String, String>() {
            public void onRemoval(RemovalNotification<String, String> notification) {
                System.out.println("[" + notification.getKey() + ":" + notification.getValue() + "] is removed!");
            }
        };
        Cache<String,String> cache = CacheBuilder.newBuilder()
                .maximumSize(3)
                .removalListener(listener)
                .build();
        Object value = new Object();
        cache.put("key1","value1");
        cache.put("key2","value2");
        cache.put("key3","value3");
        cache.put("key4","value3");
        cache.put("key5","value3");
        cache.put("key6","value3");
        cache.put("key7","value3");
        cache.put("key8","value3");
    }
}

removalListener方法爲Cache指定了一個移除監聽器,這樣當有記錄從Cache中被刪除時,監聽器listener就會感知到這個事件。程序運行結果以下圖所示。
圖片描述

自動加載

Cache的get方法有兩個參數,第一個參數是要從Cache中獲取記錄的key,第二個記錄是一個Callable對象。當緩存中已經存在key對應的記錄時,get方法直接返回key對應的記錄。若是緩存中不包含key對應的記錄,Guava會啓動一個線程執行Callable對象中的call方法,call方法的返回值會做爲key對應的值被存儲到緩存中,而且被get方法返回。下面是一個多線程的例子:

public class StudyGuavaCache {

    private static Cache<String,String> cache = CacheBuilder.newBuilder()
            .maximumSize(3)
            .build();

    public static void main(String[] args) throws InterruptedException {

        new Thread(new Runnable() {
            public void run() {
                System.out.println("thread1");
                try {
                    String value = cache.get("key", new Callable<String>() {
                        public String call() throws Exception {
                            System.out.println("load1"); //加載數據線程執行標誌
                            Thread.sleep(1000); //模擬加載時間
                            return "auto load by Callable";
                        }
                    });
                    System.out.println("thread1 " + value);
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                System.out.println("thread2");
                try {
                    String value = cache.get("key", new Callable<String>() {
                        public String call() throws Exception {
                            System.out.println("load2"); //加載數據線程執行標誌
                            Thread.sleep(1000); //模擬加載時間
                            return "auto load by Callable";
                        }
                    });
                    System.out.println("thread2 " + value);
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

這段代碼中有兩個線程共享同一個Cache對象,兩個線程同時調用get方法獲取同一個key對應的記錄。因爲key對應的記錄不存在,因此兩個線程都在get方法處阻塞。此處在call方法中調用Thread.sleep(1000)模擬程序從外存加載數據的時間消耗。代碼的執行結果以下圖:
圖片描述

從結果中能夠看出,雖然是兩個線程同時調用get方法,但只有一個get方法中的Callable會被執行(沒有打印出load2)。Guava能夠保證當有多個線程同時訪問Cache中的一個key時,若是key對應的記錄不存在,Guava只會啓動一個線程執行get方法中Callable參數對應的任務加載數據存到緩存。當加載完數據後,任何線程中的get方法都會獲取到key對應的值。

統計信息

能夠對Cache的命中率、加載數據時間等信息進行統計。在構建Cache對象時,能夠經過CacheBuilder的recordStats方法開啓統計信息的開關。開關開啓後Cache會自動對緩存的各類操做進行統計,調用Cache的stats方法能夠查看統計後的信息。

public class StudyGuavaCache {
    public static void main(String[] args) throws InterruptedException {
        Cache<String,String> cache = CacheBuilder.newBuilder()
                .maximumSize(3)
                .recordStats() //開啓統計信息開關
                .build();
        cache.put("key1","value1");
        cache.put("key2","value2");
        cache.put("key3","value3");
        cache.put("key4","value4");

        cache.getIfPresent("key1");
        cache.getIfPresent("key2");
        cache.getIfPresent("key3");
        cache.getIfPresent("key4");
        cache.getIfPresent("key5");
        cache.getIfPresent("key6");

        System.out.println(cache.stats()); //獲取統計信息
    }
}

程序執行結果以下圖所示:
圖片描述

這些統計信息對於調整緩存設置是相當重要的,在性能要求高的應用中應該密切關注這些數據

LoadingCache

LoadingCache是Cache的子接口,相比較於Cache,當從LoadingCache中讀取一個指定key的記錄時,若是該記錄不存在,則LoadingCache能夠自動執行加載數據到緩存的操做。LoadingCache接口的定義以下:

public interface LoadingCache<K, V> extends Cache<K, V>, Function<K, V> {

    V get(K key) throws ExecutionException;

    V getUnchecked(K key);

    ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException;

    V apply(K key);

    void refresh(K key);

    @Override
    ConcurrentMap<K, V> asMap();
}

與構建Cache類型的對象相似,LoadingCache類型的對象也是經過CacheBuilder進行構建,不一樣的是,在調用CacheBuilder的build方法時,必須傳遞一個CacheLoader類型的參數,CacheLoader的load方法須要咱們提供實現。當調用LoadingCache的get方法時,若是緩存不存在對應key的記錄,則CacheLoader中的load方法會被自動調用從外存加載數據,load方法的返回值會做爲key對應的value存儲到LoadingCache中,並從get方法返回。

public class StudyGuavaCache {
    public static void main(String[] args) throws ExecutionException {
        CacheLoader<String, String> loader = new CacheLoader<String, String> () {
            public String load(String key) throws Exception {
                Thread.sleep(1000); //休眠1s,模擬加載數據
                System.out.println(key + " is loaded from a cacheLoader!");
                return key + "'s value";
            }
        };

        LoadingCache<String,String> loadingCache = CacheBuilder.newBuilder()
                .maximumSize(3)
                .build(loader);//在構建時指定自動加載器

        loadingCache.get("key1");
        loadingCache.get("key2");
        loadingCache.get("key3");
    }
}

程序執行結果以下圖所示:
圖片描述

相關文章
相關標籤/搜索