Spring事件
1、关键类:
ApplicationEvent:事件源
ApplicationListener:编码式事件监听及处理(业务逻辑处理)
@EventListener:注解式事件监听及处理
ApplicationContext:spring容器,用于发布事件
2、遵循流程:
自定义事件,继承ApplicationEvent
定义监听事件,实现ApplicationListener
定义消息,发到容器中,使容器触发事件
发布事件,使用ApplicationContext发布事件
3、异步处理
默认Spring事件是同步处理
异步关键:开启@EnableAsync;方法上添加Async
4、实例
(1)事件类
@Data
public class MessEvent extends ApplicationEvent {
private Long postId;
private Long fromUserId;
private Long toUserId;
private int type;//0:评论事件,1:其他事件
public MessEvent(Object source,int type) {
super(source);
this.type = type;
}
}
(2)事件监听类
//主键注入到容器,容器才能传播事件
@Component
@Slf4j
public class MessEventListener implements ApplicationListener<MessEvent> {
@Override
public void onApplicationEvent(MessEvent messEvent) {
//messEvent.toString()指事件的消息
System.out.println("接收到事件----" + messEvent.toString());
log.debug("接收到事件----" + messEvent.toString());//调试
}
}
(3)Spring容器发布事件,在启动类内添加容器
@RestController
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
System.out.println("hello,旧时光!");
}
//添加容器
@Autowired
ApplicationContext applicationContext;
@GetMapping("/test")
public Object test(){
MessEvent event = new MessEvent(this,0);
event.setPostId(1L);
event.setFromUserId(99L);
applicationContext.publishEvent(event);
System.out.println("Spring事件-------");
return "你是认真的吗?";
}
}
启动该项目,访问地址http://localhost:8099/test,运行结果如下所示:
修改成同步事件
(1)修改启动类
添加注解:@Slf4j
输出形式改成如下:
log.info("Spring事件-------test");
(2)修改监听事件类
//System.out.println("接收到事件----" + messEvent.toString());
log.info("接收到事件----" + messEvent.toString());//调试
启动该项目,访问地址http://localhost:8099/test,运行结果如下所示:
修改成异步事件
(1)修改启动类
添加注解:@EnableAsync
(2)修改监听事件类
添加注解:
@Async
@Override
启动该项目,访问地址http://localhost:8099/test,运行结果如下所示: