1,概述
事件发布和订阅具体流程:
1,具体要发布的事件,事件中携带发送的数据
2,发送事件
3,监听器,监听发布的事件;获取事件的携带数据,执行业务逻辑
发布(事件作为参数)
事件
监听(事件作为参数)
例如:使用切面记录系统日志 ===》 发送相同类型的事件(携带的日志信息) ===》 发布事件 ===》
监听器拿到日志信息 ====》 操作日志(打印及存库)
2,事件
/**
* @Description: 事件,主要封装传递监听器需要的 ##对象和数据## ,作为监听器监听的目标
*/
public class MyApplicationEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
private String msg;
private long executeTime;
public long getExecuteTime() {
return executeTime;
}
public String getMsg() {
return msg;
}
public MyApplicationEvent(Object source, String msg, long executeTime) {
super(source);
this.msg = msg;
this.executeTime = executeTime;
}
}
3,发布(发布事件)
/**
* @date 2021/12/8 17:53
* @author: zhanghw
* @Description: 发布
*/
@Component
public class EventPublish {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
/**
* 事件发布
*/
public void eventPublish(Object source, String msg, long time) {
applicationEventPublisher.publishEvent(new MyApplicationEvent(source, msg, time));
}
}
4,监听(监听事件)
/**
* @date 2021/12/8 17:10
* @author: zhanghw
* @Description: 监听器 具体根据事件发生的业务处理模块,可以接受事件的参数数据处理业务逻辑
*/
@Component
public class MyListener implements ApplicationListener<MyApplicationEvent> {
@Override
public void onApplicationEvent(MyApplicationEvent applicationEvent) {
System.out.println("执行目标类"+applicationEvent.getSource()
+"执行耗时"+applicationEvent.getExecuteTime()+
"事件消息"+applicationEvent.getMsg());
}
// 封装存库
......
}
5,测试(发布事件)
/**
* @date 2021/12/8 18:07
* @author: zhanghw
* @Description: 发布事件
*/
@RestController
public class ListenerTest {
@Autowired
private EventPublish eventPublish;
@RequestMapping("test")
public String a() {
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
System.out.println("cccccccccc");
}
long end = System.currentTimeMillis();
eventPublish.eventPublish(this.getClass(), "消息", (long) (end - start));
return "success";
}
}
6,监听的第二种方式(注解)
/**
* @Description: 注解监听
*/
@Configuration
public class MyListener2 {
@EventListener(value = {MyApplicationEvent.class})
public void onApplicationEvent(MyApplicationEvent applicationEvent) {
System.out.println("注解自定义监听器 事件被触发==========》"+applicationEvent.getSource()+"===========>"+applicationEvent.getExecuteTime()+"====>"+applicationEvent.getMsg());
}
}
## @EventListener注解的value是一个数组可以指定要监听的多个事件;ApplicationEvent.class监听所有事件