缓存
Guava Cache提供了内存缓存功能。内存缓存需要考虑很多问题,包括并发问题,缓存失效机制,内存不够用时缓存释放,缓存的命中率,缓存的移除等等。 当然这些东西Guava都考虑到了。
Guava Cache与ConcurrentMap很相似,但也不完全一样。最基本的区别是ConcurrentMap会一直保存所有添加的元素,直到显式地移除。相对地,Guava Cache为了限制内存占用,通常都设定为自动回收元素。
使用方法如下:
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);
}
});
这样就得到一个缓存对象,可以对其进行操作了:
//获取缓存项
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...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。