Spring Boot + EventBus使用教程

简介

EventBus是一个基于发布订阅的事件总线,在Java和Android里都可以使用。
EventBus:https://github.com/greenrobot/EventBus

EventBus

使用

引入pom

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

定义事件监听类

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

EventBusConfig

1
2
3
4
5
6
7
8
@Configuration
public class EventBusConfig {

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

EventHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@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");
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
@RunWith(SpringRunner.class)
@SpringBootTest
public class EventBusTest {

@Autowired
private EventHandler eventHandler;

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

运行结果

1
2
2019-11-01 22:33:28.657  INFO 6656 --- [     main] cn.appblog.test.eventbus.EventListener   : Subscribe message:test
2019-11-01 22:33:28.671 INFO 6656 --- [ main] cn.appblog.test.eventbus.EventHandler : post event

自定义事件

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

添加MessageEvent类

1
2
3
4
5
6
7
@Data
@Builder
public class MessageEvent {

private Integer id;
private String name;
}

修改EventHandler里的eventPost方法

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

修改EventListener类里的onMessageEvent方法

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

运行测试类,查看结果

1
2
2019-11-01 22:53:28.273  INFO 2252 --- [     main] cn.appblog.test.eventbus.EventListener   : Subscribe message:MessageEvent(id=1, name=test)
2019-11-01 22:53:28.278 INFO 2252 --- [ main] cn.appblog.test.eventbus.EventHandler : post event

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :