Guava-EventBus简单学习笔记

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。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值