前言
在实际业务开发中,业务比较复杂下,核心业务处理完成,需要处理其他若干子业务,如果平铺式的堆叠在一起,可能导致代码很长,耦合度加大,维护难度几何倍数加大。
Spring Event 同步使用
Spring Event 是一个观察者模式,一个Bean处理完成后希望其他Bean能够得到通知,或者说这个Bean的这个行为能被其他Bean观察着,并作出响应。
自定义事件
@Data
@ToString
public class OrderProductEvent extends ApplicationEvent {
/** 订单id **/
private String orderId;
public OrderProductEvent(Object source, String orderId) {
super(source);
this.orderId = orderId;
}
}
定义监听器
@Slf4j
@Component
public class OrderProductListener implements ApplicationListener<OrderProductEvent> {
@SneakyThrows
@Override
public void onApplicationEvent(OrderProductEvent event) {
String orderId = event.getOrderId();
long start = System.currentTimeMillis();
Thread.sleep(2000);
long end = System.currentTimeMillis();
log.info("{}:校验订单商品价格耗时:({})毫秒", orderId, (end - start));
}
}
发布事件
public class OrderService {
/** 注入ApplicationContext用来发布事件 */
private final ApplicationContext applicationContext;
public String buyOrder(String orderId) {
long start = System.currentTimeMillis();
// 1.查询订单详情
// 2.检验订单价格 (同步处理)
applicationContext.publishEvent(new OrderProductEvent(this, orderId));
// 3.短信通知(异步处理)
long end = System.currentTimeMillis();
log.info("任务全部完成,总耗时:({})毫秒", end - start);
return "购买成功";
}
}
Spring Event 异步使用
自定义事件
@Data
@AllArgsConstructor
public class MsgEvent {
/** 该类型事件携带的信息 */
public String orderId;
}
监听器
@Slf4j
@Component
public class MsgListener {
@SneakyThrows
@EventListener(MsgEvent.class)
public void sendMsg(MsgEvent event) {
String orderId = event.getOrderId();
long start = System.currentTimeMillis();
log.info("开发发送短信");
log.info("开发发送邮件");
Thread.sleep(4000);
long end = System.currentTimeMillis();
log.info("{}:发送短信、邮件耗时:({})毫秒", orderId, (end - start));
}
}
发布事件
public String buyOrder(String orderId) {
long start = System.currentTimeMillis();
// 1.查询订单详情
// 2.检验订单价格 (同步处理)
applicationContext.publishEvent(new OrderProductEvent(this, orderId));
// 3.短信通知(异步处理)
applicationContext.publishEvent(new MsgEvent(orderId));
long end = System.currentTimeMillis();
return "true";
}
开启异步
@EnableAsync
@SpringBootApplication
public class MingYueSpringbootEventApplication {
public static void main(String[] args) {
SpringApplication.run(MingYueSpringbootEventApplication.class, args);
}
}
异步监听器
@Async
@SneakyThrows
@EventListener(MsgEvent.class)
public void sendMsg(MsgEvent event) {
String orderId = event.getOrderId();
Thread.sleep(4000);
}