最近在工作中碰到个问题,要在一个异步任务结束后,执行特定的操作。项目中没有用到Redis,又是单体应用,可以用基于Java的发布订阅组件,于是想到了Guava EventBus。
整合Guava EventBus的流程如下:
一、添加maven依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
二、创建EventBus Bean
在Spring Boot 配置类中,创建一个 EventBus 的 Bean。这样,EventBus 就可以被注入到其他 Spring 管理的组件中。
import com.google.common.eventbus.EventBus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EventBusConfig {
@Bean("myEventBus")
public EventBus eventBus() {
return new EventBus();
}
}
三、注册订阅者
先定义一个事件消息类(简单的POJO类即可),用于发送接收消息。
@Data
public class MyEvent {
private String message;
}
在Spring 组件中,通过 @Autowired
注入 EventBus,并注册订阅者。在组件的初始化方法( @PostConstruct
注解的方法)中完成订阅者的注册。
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyEventListener {
private final EventBus eventBus;
@Autowired
public MyEventListener (EventBus eventBus) {
this.eventBus = eventBus;
}
@PostConstruct
public void init() {
//注册订阅者
eventBus.register(this);
}
@Subscribe
public void handleEvent(MyEvent event) {
// 处理监听事件(业务逻辑)
}
}
四、发布事件消息
可以在任何 Spring 管理的组件中注入 EventBus 并发布事件。现在定义一个专门的Service用来发布消息。在需要发送消息的地方用这个Service发送消息即可。
import com.google.common.eventbus.EventBus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyEventService {
private final EventBus eventBus;
@Autowired
public MyEventService(EventBus eventBus) {
this.eventBus = eventBus;
}
public void publishEvent(MyEvent event) {
eventBus.post(event);
}
}
@Service
Public TestService{
@Autowired
private MyEventService myEventService;
public test(){
//一堆业务代码
//需要发消息的地方
myEventService.publishEvent(new MyEvent("发送的消息"));
}
}
现在,当 MyEventService
的 publishEvent
方法被调用时,所有像在第三步中被EventBus
注册了的订阅者的 handleEvent
方法都将被调用。
至此整合完成。Guava EventBus是一个简单轻便的发布订阅实现,在单体应用中使用很方便。