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 //配置支持异步