一、简介

EventBus是一个基于发布订阅的事件总线,在Java和Android里都可以使用。
【20200127】SpringBoot   EventBus - 图1

二、使用

1.引入pom

  1. <dependency>
  2. <groupId>org.greenrobot</groupId>
  3. <artifactId>eventbus</artifactId>
  4. <version>3.1.1</version>
  5. </dependency>

2.定义事件监听类

  1. @Component
  2. @Slf4j
  3. public class EventListener {
  4. @Subscribe
  5. public void onMessageEvent(String event) {
  6. log.info("Subscribe message:{}", event);
  7. }
  8. }

3.EventBusConfig

  1. @Configuration
  2. public class EventBusConfig {
  3. @Bean
  4. public EventBus eventBus(){
  5. return new EventBus();
  6. }
  7. }

4.EventHandler

  1. @Component
  2. @Slf4j
  3. public class EventHandler {
  4. @Autowired
  5. private EventBus eventBus;
  6. @Autowired
  7. private EventListener eventListener;
  8. @PostConstruct
  9. public void init() {
  10. eventBus.register(eventListener);
  11. }
  12. @PreDestroy
  13. public void destroy() {
  14. eventBus.unregister(eventListener);
  15. }
  16. public void eventPost(){
  17. eventBus.post("test");
  18. log.info("post event");
  19. }
  20. }

5.测试类

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class EventBusTest {
  4. @Autowired
  5. private EventHandler eventHandler;
  6. @Test
  7. public void postEvent(){
  8. eventHandler.eventPost();
  9. }
  10. }

6.运行结果

  1. 2019-11-01 22:33:24.657 INFO 6656 --- [ main] com.sww.bizhi.eventbus.EventListener : Subscribe message:test
  2. 2019-11-01 22:33:24.671 INFO 6656 --- [ main] com.sww.bizhi.eventbus.EventHandler : post event

三、自定义事件

上面的例子,我们发送和接收的都是string,如果我想event是个bean,怎么操作?

1.添加MessageEvent类

  1. @Data
  2. @Builder
  3. public class MessageEvent {
  4. private Integer id;
  5. private String name;
  6. }

2.修改EventHandler里的eventPost方法(红色字体部分)

  1. public void eventPost(){
  2. eventBus.post(MessageEvent.builder().id(1).name("test").build());
  3. log.info("post event");
  4. }

3.修改EventListener类里的onMessageEvent方法(红色字体部分)

  1. @Subscribe
  2. public void onMessageEvent(MessageEvent event) {
  3. log.info("Subscribe message:{}", event);
  4. }

4.运行测试类,查看结果

  1. 2019-11-01 22:53:24.273 INFO 2252 --- [ main] com.sww.bizhi.eventbus.EventListener : Subscribe message:MessageEvent(id=1, name=test)
  2. 2019-11-01 22:53:24.278 INFO 2252 --- [ main] com.sww.bizhi.eventbus.EventHandler : post event

四、最后

本篇初步介绍了如何在springboot里使用eventbus。
EventBus地址:https://github.com/greenrobot/EventBus
另外,本篇教程使用了lombok插件。

参考资料