kuangren 2019-11-01
EventBus是一个基于发布订阅的事件总线,在Java和Android里都可以使用。
<dependency> <groupId>org.greenrobot</groupId> <artifactId>eventbus</artifactId> <version>3.1.1</version> </dependency>
@Component @Slf4j public class EventListener { @Subscribe public void onMessageEvent(String event) { log.info("Subscribe message:{}", event); } }
@Configuration public class EventBusConfig { @Bean public EventBus eventBus(){ return new EventBus(); } }
@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"); } }
@RunWith(SpringRunner.class) @SpringBootTest public class EventBusTest { @Autowired private EventHandler eventHandler; @Test public void postEvent(){ eventHandler.eventPost(); } }
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,怎么操作?
@Data @Builder public class MessageEvent { private Integer id; private String name; }
public void eventPost(){ eventBus.post(MessageEvent.builder().id(1).name("test").build()); log.info("post event"); }
@Subscribe public void onMessageEvent(MessageEvent event) { log.info("Subscribe message:{}", event); }
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插件。