有用的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

相关文章
相关标签/搜索