Guava关于JAVA中系统组件之间交互通讯(非线程之间通讯)

Guava EventBus组件
// Class is typically registered by the container.
class EventBusChangeRecorder {
  @Subscribe public void recordCustomerChange(ChangeEvent e) {
    recordChange(e.getChange());
  }
}
// somewhere during initialization
eventBus.register(new EventBusChangeRecorder());
// much later
public void changeCustomer() {
  ChangeEvent event = getChangeEvent();
  eventBus.post(event);
}
使用方式,定义evenBus实例,通过register方法将需要调用的组件注册到eventBus中,然后使用eventBus.post(event)方式实现组件交互,event 问一个时间参数,可以理解为,上列中EventBusChangeRecord.recordCustomerChange 的ChangeEvent 参数。
 
 
 官网文档:
EventBus  allows publish-subscribe-style communication between components without requiring the components to explicitly register with one another (and thus be aware of each other). It is designed exclusively to replace traditional Java in-process event distribution using explicit registration. It is  not a general-purpose publish-subscribe system, nor is it intended for interprocess communication.
@Subscribe 定义当调用eventBus.post时,使用EventBusChangeRecorder中的哪个方法进行相应。
EventBus内部机制:
调用EventBus.register : 将需要调用的组件传入,如上列中的EventBusChangeRecorder对象实例,EventBus会通过反射以及上面的@Subscribe注释,得到一个SetMultiMap<Class<?> , EventHandler> 的集合。简单说就是找出需要调用组件的哪个方法,如recordCustomerChange(ChangeEvent e)

需要注意的是,通过这个方法要求传入的组件的接口方法有且只能有一个参数。
调用EventBus 的 post(Object event)方法 : 这里面有两部,找到任何可能的方法和参数组合将组合放到一个ConcurrentLinkedQueue<EventWithHandler>中,然后循环从Queue中拿出EventWithHandler 进行调用。

就这么简单~~ , 这所有的事情是在一个线程中完成的,只是EvenBus 为它的成员变量使用了 ThreadLocal 保证线程并发下的问题。
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值