目录
-
前言
-
Spring Event 同步使用
-
Spring Event 异步使用
前言
实际业务开发过程中,业务逻辑可能非常复杂,核心业务 + N 个子业务。如果都放到一块儿去做,代码可能会很长,耦合度不断攀升,维护起来也麻烦,甚至头疼。还有一些业务场景不需要在一次请求中同步完成,比如邮件发送、短信发送等。
MQ 确实可以解决这个问题,但 MQ 重啊,非必要不提升架构复杂度。针对这些问题,我们了解一下 Spring Event。
Spring Event 同步使用
Spring Event(Application Event)其实就是一个观察者设计模式,一个 Bean 处理完成任务后希望通知其它 Bean 或者说一个 Bean 想观察监听另一个Bean 的行为。
Spring Event 用来解耦业务真的贼好用!
Demo 地址:
https://gitee.com/csps/mingyue-springboot-learning
| 自定义事件
定义事件,继承 ApplicationEvent 的类成为一个事件类:
import lombok.Data;
import lombok.ToString;
import org.springframework.context.ApplicationEvent;
/**
* @author Strive
* @date 2022/4/22 18:00
* @description
*/
@Data
@ToString
public class OrderProductEvent extends ApplicationEvent {
/** 该类型事件携带的信息 */
private String orderId;
public OrderProductEvent(Object source, String orderId) {
super(source);
this.orderId = orderId;
}
}
| 定义监听器
监听并处理事件,实现 ApplicationListener 接口或者使用 @EventListener 注解:
import com.csp.mingyue.event.events.OrderProductEvent;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* 实现 ApplicationListener 接口,并指定监听的事件类型
*
* @author Strive
* @date 2022/4/24 09:09
* @description
*/
@Slf4j
@Component
public class OrderProductListener implements ApplicationListener<OrderProductEvent> {
/** 使用 onApplicationEvent 方法对消息进行接收处理 */
@SneakyThrows
@Override
public void onApplicationEvent(OrderProductEvent eve