springboot整合Guava EventBus实现发布订阅模式

最近在工作中碰到个问题,要在一个异步任务结束后,执行特定的操作。项目中没有用到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是一个简单轻便的发布订阅实现,在单体应用中使用很方便。

  • 14
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值