Spring Event使用
lijunyi2023-02-24SpringSpring Spring Event
(Application Event
)其实就是一个观察者设计模式,一个 Bean
处理完成任务后希望通知其它 Bean
或者说一个 Bean
想观察监听另一个Bean
的行为。
- 定义事件,继承
ApplicationEvent
的类成为一个事件类
@Data
@ToString
public class OrderProductEvent extends ApplicationEvent {
private String orderId;
public OrderProductEvent(Object source, String orderId) {
super(source);
this.orderId = orderId;
}
}
- 监听并处理事件,实现
ApplicationListener
接口或者使用 @EventListener
注解
* 实现 ApplicationListener 接口,并指定监听的事件类型
*/
@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));
}
}
- 发布事件,通过
ApplicationEventPublisher
发布事件
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderService {
private final ApplicationContext applicationContext;
* 下单
*
* @param orderId 订单ID
*/
public String buyOrder(String orderId) {
long start = System.currentTimeMillis();
applicationContext.publishEvent(new OrderProductEvent(this, orderId));
long end = System.currentTimeMillis();
log.info("任务全部完成,总耗时:({})毫秒", end - start);
return "购买成功";
}
}
@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));
}
}
public String buyOrder(String orderId) {
long start = System.currentTimeMillis();
applicationContext.publishEvent(new OrderProductEvent(this, orderId));
applicationContext.publishEvent(new MsgEvent(orderId));
long end = System.currentTimeMillis();
log.info("任务全部完成,总耗时:({})毫秒", end - start);
return "购买成功";
}