利用SpringBoot Event解耦

111 阅读1分钟

Spring Event

  • registerService在完成自身的用户注册逻辑之后,只需要发送一个userRegisterEvent事件,无需再关注其他拓展逻辑。
  • EmailSendService、CouponsSendService等监听用户注册事件。

定义一个事件模型

@Data
@AllArgsConstructor
public class MsgEvent {
    private String orderId;
}
public interface SendMsgPushEvent {

    /**
     * 发送
     * @param doctorUserId
     */
    void pushMsg(Long userId);
}
@RequiredArgsConstructor
@Slf4j
@Service
public class OrderProductPushEvent implements SendMsgPushEvent{


    private final ApplicationEventPublisher applicationEventPublisher;

    /**
     * 下单
     *
     * @param orderId 订单ID
     */
    public String pushMsg(String orderId) {
        long start = System.currentTimeMillis();
        // 2.检验订单价格 (同步处理)
        applicationEventPublisher.publishEvent(new OrderProductEvent(this,orderId));
        // 3.短信通知(异步处理)
        applicationEventPublisher.publishEvent(new MsgEvent(orderId));
        long end = System.currentTimeMillis();
        log.info("任务全部完成,总耗时:({})毫秒", end - start);
        return "购买成功";
    }
}
@Slf4j
@Component
public class MsgListener {

    /**
     * 监听发送邮件的事件,如果有则直接发送
     * @param event
     * @throws InterruptedException
     */
    @EventListener(MsgEvent.class)
    @Async
    public void sendMsg(MsgEvent event) throws InterruptedException {
        String orderId = event.getOrderId();
        long start = System.currentTimeMillis();
        log.info("开发发送短信提醒");
        log.info("开发发送邮件提醒");
        Thread.sleep(2000);
        long end = System.currentTimeMillis();
        log.info("{}:发送短信、邮件耗时:({})毫秒", orderId, (end - start));
    }
}