Yarn状态机 #20
@ -33,7 +33,7 @@ public interface EventHandler<T extends Event> {
|
|||||||
|
|
||||||
AsyncDispatcher 实现了接口Dispatcher,Dispatcher中定义了事件Dispatcher的接口。主要提供两个功能:
|
AsyncDispatcher 实现了接口Dispatcher,Dispatcher中定义了事件Dispatcher的接口。主要提供两个功能:
|
||||||
- 注册不同类型的事件。
|
- 注册不同类型的事件。
|
||||||
- 获取所有的事件处理器。
|
- 获取事件处理器,用来派发事件,等待异步执行真正的EventHandler。
|
||||||
|
|
||||||
```java
|
```java
|
||||||
@Public
|
@Public
|
||||||
@ -47,7 +47,8 @@ public interface Dispatcher {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
AsyncDispatcher实现了Dispatcher接口,也扩展了AbstractService,表明AsyncDispatcher也是一个服务:
|
AsyncDispatcher实现了Dispatcher接口,也扩展了AbstractService,表明AsyncDispatcher也是一个服务,
|
||||||
|
是一个典型的生产者消费这模型。
|
||||||
|
|
||||||
```java
|
```java
|
||||||
public class AsyncDispatcher extends AbstractService implements Dispatcher {
|
public class AsyncDispatcher extends AbstractService implements Dispatcher {
|
||||||
@ -55,4 +56,44 @@ public class AsyncDispatcher extends AbstractService implements Dispatcher {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
# 事件处理器的注册
|
||||||
|
|
||||||
|
事件注册就是将事件写入到eventDispatchers里面,eventDispatchers的定义:`Map<Class<? extends Enum>, EventHandler> eventDispatchers`,
|
||||||
|
键是事件类型,value是事件的处理器。
|
||||||
|
|
||||||
|
对于同一事件类型注册多次handler处理函数时,将使用MultiListenerHandler代替,MultiListenerHandler里面保存了多个handler,调用handler函数时,
|
||||||
|
会依次调用每个handler。
|
||||||
|
|
||||||
|
```java
|
||||||
|
public void register(Class<? extends Enum> eventType,
|
||||||
|
EventHandler handler) {
|
||||||
|
/* check to see if we have a listener registered */
|
||||||
|
EventHandler<Event> registeredHandler = (EventHandler<Event>) eventDispatchers.get(eventType);
|
||||||
|
LOG.info("Registering " + eventType + " for " + handler.getClass());
|
||||||
|
if (registeredHandler == null) {
|
||||||
|
eventDispatchers.put(eventType, handler);
|
||||||
|
} else if (!(registeredHandler instanceof MultiListenerHandler)){
|
||||||
|
/* for multiple listeners of an event add the multiple listener handler */
|
||||||
|
MultiListenerHandler multiHandler = new MultiListenerHandler();
|
||||||
|
multiHandler.addHandler(registeredHandler);
|
||||||
|
multiHandler.addHandler(handler);
|
||||||
|
eventDispatchers.put(eventType, multiHandler);
|
||||||
|
} else {
|
||||||
|
/* already a multilistener, just add to it */
|
||||||
|
MultiListenerHandler multiHandler
|
||||||
|
= (MultiListenerHandler) registeredHandler;
|
||||||
|
multiHandler.addHandler(handler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
# 事件处理
|
||||||
|
|
||||||
|
AsyncDispatcher#getEventHandler()是异步派发的关键:
|
||||||
|
|
||||||
|
```java
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user