Springboot中事件Event的相关使用

1. 标题

实际项目开发中,有的服务方法不需要在一次请求中同步完成,比如邮件发送或 短信发送,订单和仓库更新
等,不需要在请求处理业务参数时同步去执行,这个使用可以使用线程或者事件或者MQ消息队列来实现。
但是如果业务比较简单,使用MQ这种比较重的技术 反而得不偿失  这个时候事件Event就是一个比较好的
选择

2.实现

事件Event其实也是线程,通过异步执行的方式,减少业务的冗余,使请求专注核心业务代码的操作,提高系统的响应速度

1. 创建事件基类

 /**
   *  事件基类  用于传输事件业务中所需的内容  
   *    继承ApplicationEvent
   */
@Getter
@Setter
public class PushMsgEvent extends ApplicationEvent {
    /**
     *  用于接收 事件中所需要的业务数据
     */
    private String userId;
 
    public PushMsgEvent(Object source) {
        super(source);
    }
    public PushMsgEvent(Object source, String userId) {
        super(source);
        this.userId= userId;
    }
}

2. 创建事件发现类

@Component
public class PushMsgPublisher implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher publisher;
    /**
     * 创建事件
     * @param source
     * @param userId   业务数据
     */
    public void publish(Object source, String userId){
        publisher.publishEvent(new PushMsgEvent(this,userId));
    }
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }
}

3. 创建事件监听类

   /**
     * 事件监听器,事件创建后  监听器监听到存在事件 执行业务代码
     */
	@Component
	public class PushMsgListener implements ApplicationListener<PushMsgEvent>, ApplicationContextAware {
	
	    public ApplicationContext applicationContext;
	    @Override
	    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	        this.applicationContext = applicationContext;
	    }
	
	    @Async
	    @Override
	    public void onApplicationEvent(PushMsgEvent pushMsgEvent) {
	     		 // TODO 此处编写需要处理业务代码
	     		 
	    }
	}

4. 异步事件的配置

	在监听器中的onApplicationEvent方法中添加  @Async注解,表示异步执行 
	
	同时在Springboot启动类上添加注解 @EnableAsync   //配置支持异步
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值