提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
概念
使用EventBus(Guava提供的)可以实现事件的发布和监听,概念、效果和Spring的事件(可点击参看另一篇文章)很类似。
EventBus的事件机制是A调用一个发布事件的方法,就能自动调用B监听这个事件的方法,这个过程有3个对象:
- 事件本身,其实就是一个对象,这是一个普通的java类;
- 发布事件的对象,使用 EventBus 的 post 方法来发布,参数就是事件;
- 接收(或者叫监听)事件的对象,使用@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岁。
总的看来,使用还是很简单的。