article/java/springboot-事件.md
2024-08-30 21:19:44 +08:00

114 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## springboot事件
#### 事务本身
实现 ApplicationEvent 类
```java
@Getter
public static class SchSyncToUpcomingEndEvent extends ApplicationEvent {
public SchSyncToUpcomingEndEvent(Object source) {
super(source);
}
}
```
#### 事务发布
```java
applicationEventPublisher.publishEvent()
applicationEventMulticaster.multicastEvent()
```
#### 注解接收事件
默认同步处理 需要异步处理 添加@Async 注解
```
/**
* 监听 SCH 同步至航班计划完成事件。
* 开始 航班计划同步至算法
*
* @param event
*/
@Async
@EventListener(FlightPlanEvent.SchSyncToUpcomingEndEvent.class)
public void syncCurrentStatusToAlgListener(FlightPlanEvent.SchSyncToUpcomingEndEvent event) {
XxlJobHelper.log("同步当前航班状态至算法 开始");
XxlJobHelper.log("同步当前航班状态至算法 结束");
}
```
#### 编程式接收事务
监听器
```java
@Component
@Slf4j
public class EventListener implements ApplicationListener<CustomEvent>{
@Override
public void onApplicationEvent(CustomEvent event) {
//这里也可以监听所有事件 使用 ApplicationEvent 类即可
//这里仅仅监听自定义事件 CustomEvent
log.info("ApplicationListener方式监听事件{}", event);
}
}
```
注册监听器
```java
@SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication app =new SpringApplication(Application.class);
app.addListeners(new MyApplicationStartingEventListener());//加入自定义的监听类
app.run(args);
}
}
```
#### 事务事件
需要等 事务发布者的事务完成提交 才能接收到事件
事务事件 只能接收一次
```
@Async
@TransactionalEventListener(value = FlightPlanEvent.SchSyncToUpcomingEndEvent.class, phase = TransactionPhase.AFTER_COMMIT)
public void syncBaseDataUpdateListener(FlightPlanEvent.SchSyncToUpcomingEndEvent event) {
syncBaseData();
syncSchRouteToRedis();
}
```