EventBus 事件机制详解(Google Guava)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


概念

使用EventBus(Guava提供的)可以实现事件的发布和监听,概念、效果和Spring的事件(可点击参看另一篇文章)很类似。

EventBus的事件机制是A调用一个发布事件的方法,就能自动调用B监听这个事件的方法,这个过程有3个对象:

  1. 事件本身,其实就是一个对象,这是一个普通的java类;
  2. 发布事件的对象,使用 EventBus 的 post 方法来发布,参数就是事件;
  3. 接收(或者叫监听)事件的对象,使用@Subscribe注解的方法来处理接收的事件,这里需要注意提前将这个监听者注册到EventBus中;

1. 事件本身

对应3个对象中的第一个,如上所述,是一个普通的java类,如下:

package test.eventbus;

public class EventBusMessage {
    private int age;

    public EventBusMessage(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}

2. 发布事件的对象

对应3个对象的第二个,使用 EventBus 的 post 方法来发布,参数就是事件 EventBusMessage ,如下:

package test.eventbus;

import com.google.common.eventbus.EventBus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class EventBusTestController {
    @Autowired
    private EventBus eventBus; // 注意这里的EventBus是spring默认的单例

    @GetMapping("/pub-event")
    public void pub() {
        eventBus.post(new EventBusMessage(4));
    }
}

3. 接收事件的对象

对应3个对象的第三个,或者叫监听事件,就是使用@Subscribe注解的方法来处理接收的事件,这个方法的参数要和发布事件方法的参数一致,都是文中的 EventBusMessage ,还需要注意提前将这个监听者注册到EventBus中;

代码如下(示例):

package test.eventbus;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class EventBusListener {
    @Autowired
    private EventBus eventBus; // 注意这里的EventBus是spring默认的单例,和发布事件的对象是同一个

    @PostConstruct
    public void register() {
        eventBus.register(this);
    }

    @Subscribe
    public void dealEvent(EventBusMessage event) {
        System.out.println("EventBusListener收到信息了,Mcdull 今年" + event.getAge() + "岁。");
    }
}

4. 验证结果

代码就这么多了,接下来,启动项目,请求"/test/pub-event",能看到如下输出:

EventBusListener收到信息了,Mcdull 今年4岁。

总的看来,使用还是很简单的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值