76、Spring Event 解耦神器的使用

1、第一种方式

定义事件,继承 ApplicationEvent 的类成为一个事件类
@ToString
public class OrderProductEvent extends ApplicationEvent {
    /** 该类型事件携带的信息 */
    private String orderId;

    public OrderProductEvent(Object source, String orderId) {
        super(source);
        this.orderId = orderId;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
}
监听并处理事件,实现 ApplicationListener 接口
@Slf4j
@Component
public class OrderProductListener implements ApplicationListener<OrderProductEvent> {
    /** 使用 onApplicationEvent 方法对消息进行接收处理 */
    @Async
    @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));
    }
}

2、第二种使用方式(推荐使用这个)

定义事件

@Data
@AllArgsConstructor
public class MsgEvent {

    /** 该类型事件携带的信息 */
    public String orderId;
}

定义监听器

@Slf4j
@Component
public class MsgListener {


    @Async
    @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));
    }
}

3、记得在启动类上加  @EnableAsync  注解

 

4、测试Spring Event

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderService {
    /** 注入ApplicationContext用来发布事件 */
    private final ApplicationContext applicationContext;
    /**
     * 下单
     *
     * @param orderId 订单ID
     */
    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();
        log.info("任务全部完成,总耗时:({})毫秒", end - start);
        return "购买成功";
    }
}

 

posted @ 2022-08-23 20:48  shunnWcs  阅读(29)  评论(0)    收藏  举报