SpringBoot+EventBus使用教程(一)
一、简介
EventBus是一个基于发布订阅的事件总线,在Java和Android里都可以使用。
二、使用
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插件。
相关推荐
kururunga 2020-05-07
kururunga 2020-05-01
kururunga 2020-11-16
pengruiyu 2020-08-01
kururunga 2020-07-16
kururunga 2020-04-23
一个来自吉尔尼斯 2020-04-21
一个来自吉尔尼斯 2020-04-10
xiaorulou 2020-03-01
pengruiyu 2020-02-19
kururunga 2019-12-08
一个来自吉尔尼斯 2019-12-05
Androidtalent 2014-03-23
pengruiyu 2019-10-20
huangf 2015-04-17
kururunga 2015-05-17
huangf 2015-05-17
Androidtalent 2019-09-08