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 保证线程并发下的问题。