SpringBoot+EventBus使用教程(一)

kuangren 2019-11-01

一、简介

EventBus是一个基于发布订阅的事件总线,在Java和Android里都可以使用。

SpringBoot+EventBus使用教程(一)

二、使用

1.引入pom

<dependency>
            <groupId>org.greenrobot</groupId>
            <artifactId>eventbus</artifactId>
            <version>3.1.1</version>
        </dependency>

2.定义事件监听类

@Component
@Slf4j
public class EventListener {
    @Subscribe
    public void onMessageEvent(String event) {
        log.info("Subscribe message:{}", event);
    }
}

3.EventBusConfig

@Configuration
public class EventBusConfig {

    @Bean
    public EventBus eventBus(){
        return new EventBus();
    }

}

4.EventHandler

@Component
@Slf4j
public class EventHandler {

    @Autowired
    private EventBus eventBus;

    @Autowired
    private EventListener eventListener;

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

    @PreDestroy
    public void destroy() {
        eventBus.unregister(eventListener);
    }

    public void eventPost(){
        eventBus.post("test");
        log.info("post event");
    }
}

5.测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class EventBusTest {

    @Autowired
    private EventHandler eventHandler;

    @Test
    public void postEvent(){
        eventHandler.eventPost();
    }

}

6.运行结果

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

三、自定义事件

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

1.添加MessageEvent类

@Data
@Builder
public class MessageEvent {

    private Integer id;
    private String name;

}

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

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

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

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

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

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

四、最后

本篇初步介绍了如何在springboot里使用eventbus,下一篇文章将介绍如何集成spring-boot-starter-guava-eventbus

EventBus地址:https://github.com/greenrobot/EventBus

另外,本篇教程使用了lombok插件。

相关推荐