有用的Guava(二)

緩存

Guava Cache提供了內存緩存功能。內存緩存須要考慮不少問題,包括併發問題,緩存失效機制,內存不夠用時緩存釋放,緩存的命中率,緩存的移除等等。 固然這些東西Guava都考慮到了。
Guava Cache與ConcurrentMap很類似,但也不徹底同樣。最基本的區別是ConcurrentMap會一直保存全部添加的元素,直到顯式地移除。相對地,Guava Cache爲了限制內存佔用,一般都設定爲自動回收元素。
使用方法以下:git

LoadingCache<String, Student> cache = CacheBuilder.newBuilder()  
      .maximumSize(10000)
      .expireAfterWrite(10, TimeUnit.SECONDS)
      //統計緩存的命中率
      .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的實現自動加載緩存
      .build(new CacheLoader<String, Student>() {
          @Override
          public Student load(String key) throws Exception {
              return createStudentByKey(key);
              }
          });

這樣就獲得一個緩存對象,能夠對其進行操做了:github

//獲取緩存項
 Object value = cache.get("key");
 //獲取緩存的命中率等狀態;
 cache.stats();

也能夠在get()時定義數據加載源:緩存

Cache<String, Student> cache = CacheBuilder.newBuilder().maximumSize(1000).build();
    Object value = cache.get("key", new Callable<Object>() {
                            public Object call() {
                                createStudentByKey(key);
                                }
                           });

guava的內存緩存很是強大,能夠設置各類選項,使用方便。
另外還提供了下面一些方法,來方便各類須要:
--ImmutableMap<K, V> getAllPresent(Iterable<?> keys) 一次得到多個鍵的緩存值
--put和putAll方法向緩存中添加一個或者多個緩存項
--invalidate 和 invalidateAll方法從緩存中移除緩存項
--asMap()方法得到緩存數據的ConcurrentMap<K, V>快照
--cleanUp()清空緩存
--refresh(Key) 刷新緩存,即從新取緩存數據,更新緩存多線程

EventBus

EventBus是Guava框架對觀察者模式的一種實現,使用EventBus能夠很簡潔的實現事件註冊監聽和消費。Guava框架裏面提供了兩種相關的實現,一種是單線程同步事件消費,另一直是多線程異步事件消費。
消息接收方:併發

public class Event {
    @Subscribe
    public void sub(String message) {
        System.out.println(message);
    }

}

消息發起方:框架

public void testEventBus() {
        //同步
        EventBus eventBus = new EventBus();
        //異步
        //AsyncEventBus eventBus = new AsyncEventBus(Executors.newFixedThreadPool(3));
        eventBus.register(new Event());//註冊事件
        eventBus.post("ssdf");// 觸發事件處理
    }

ps:
com.google.common.eventbus.EventBus$LoggingSubscriberExceptionHandler.handleException Could not dispatch event: XXX
這個錯誤多是因爲lister中@Subscribe對應方法拋出了異常。異步

參考資料

http://ifeve.com/google-guava...
https://github.com/google/gua...ide

相關文章
相關標籤/搜索