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 保證線程併發下的問題。
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章