EventBus 介绍
EventBus 是 轻量级的Event(消息)发布/订阅框架,采用设计模式中的Observer(观察者)模式。允许组件之间进行发布-订阅式的通信,而不需要组件彼此显式的注册。
EventBus 不是一个通用的发布-订阅系统,不适用于进程间通信。
EventBus用法
这里使用Socket创建一个简单的一对一的消息发送,对EventBus进行初步了解。
public class UserThread extends Thread {
private Socket connection;
private EventBus channel;
private BufferedReader in;
private PrintWriter out;
public UserThread(Socket connection,EventBus channel){
this.connection = connection;
this.channel = channel;
try {
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
out = new PrintWriter(connection.getOutputStream(),true);
}catch (IOException e){
e.printStackTrace();
System.exit(1);
}
}
@Subscribe
public void receiveMessage(String message){
if(out != null){
System.out.println("message = [" + message + "]");
}
}
@Override
public void run() {
try {
String input;
while((input = in.readLine()) !=null ){
channel.post(input);
}
}catch (IOException e){
e.printStackTrace();
}
channel.unregister(this);
try {
connection.close();
}catch (IOException e){
e.printStackTrace();
}
in = null;
out = null;
}
}
这里使用一个简单的线程对象作为消息的接收方,线程的run方法读取Socket中消息,receiveMessage方法来对接收到的消息进行打印。
public class EventBusChat {
public static void main(String[] args) {
EventBus channel = new EventBus();
ServerSocket socket;
try{
socket = new ServerSocket(4444);
while(true){
Socket connection = socket.accept();
UserThread newUser = new UserThread(connection, channel);
channel.register(newUser);
newUser.start();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
创建一个消息接收方的实例newUser,将该实例注册到EventBus中进行消息监听。
接下来通过telnet的方式向4444
端口发送消息。
telnet localhost 4444
观察者(Object)接收Event的流程:
1、暴露一个public方法用来处理event,且只有一个Event类型的参数
2、添加@Subscribe 注解
3、将该Object的实例注册到EventBus中eventBus.register()
被观察者(Object)发送Event的流程:
1、 EventBus实例通过post方法发送Event实例:eventBus.post("event")
-
当post方法被调用后,所有监听Event方法(@Subscribe 注解的方法)依次进行处理。Event 处理的过慢将会触发Event阻塞。(使用AsyncEventBus可以有效的解决)
-
如果一个Event被post后,没有相应的处理该Event的方法,这个Event将会被包装为dead Event来重新发布。可以自定义方法来处理Dead Event
-
如果处理事件的方法接受参数为Object,则不会生成Dead Event。