用java代码模拟监听器,监听事务触发。
代码目录:
event包定义事件,PersonEvent 相对类似spark的 SparkListenerEvent
public class PersonEvent {
}
public class EatEvent extends PersonEvent{
};
public class PlayEvent extends PersonEvent{
};
listener定义监听,PersionListener 类似spark的 SparkListener
public class PersonListener {
public void doEat(){
}
public void doPlay(){
}
}
public class LogListener extends PersonListener{
public void doEat(){
System.out.println("log=============eat");
}
public void doPlay(){
System.out.println("log=============play");
}
}
public class ShowListener extends PersonListener{
public void doEat(){
System.out.println("show=============eat");
}
public void doPlay(){
System.out.println("show=============play");
}
}
PersonListenerBus 类似于spark的 SparkListenerBus 用于最终执行对应监听的对应事件
public class PersonListenerBus {
public void doPost(PersonListener listener, PersonEvent event){
if(event instanceof EatEvent){
listener.doEat();
}else if(event instanceof PlayEvent){
listener.doPlay();
}else{
System.out.println("===========nothing===========");
}
}
}
AsyncEventQueue 类似于spark AsyncEventQueue 。继承 PersonListenerBus ,调用PersonListenerBus,被LiveListenerBus调用 ,连接外部总线
public class AsyncEventQueue extends PersonListenerBus{
private String name;
private PersonListener listener;
public AsyncEventQueue(String name,PersonListener listener){
this.name=name;
this.listener = listener;
}
public void schedule(PersonEvent event){
System.out.println("===name:"+name+"==执行监听");
doPost(this.listener,event);
}
}
LiveListenerBus 类似于spark的LiveListenerBus,提供注册监听监口,以及监听执行。
public class LiveListenerBus {
public CopyOnWriteArrayList<AsyncEventQueue> queues = new CopyOnWriteArrayList<AsyncEventQueue>();
public void registListener(String name, PersonListener listener){
queues.add(new AsyncEventQueue(name,listener));
}
public void doEvent(PersonEvent event){
Iterator<AsyncEventQueue> it = queues.iterator();
while (it.hasNext()){
it.next().schedule(event);
}
}
}
模拟效果: