在实际业务开发过程中,业务逻辑可能非常复杂,核心业务+N个子业务。如果全部放在一起,代码可能会很长,耦合度会不断上升,维护起来会很麻烦,甚至很头疼。还有一些业务场景不需要在一个请求中同步完成,比如发送邮件、短信等。MQ确实可以解决这个问题,但是MQ比较重,没必要增加架构的复杂度。针对这些问题,我们来看看SpringEvent。SpringEvent的同步使用SpringEvent(ApplicationEvent)其实是一种观察者设计模式。一个Bean想在完成任务后通知其他Bean,或者一个Bean想观察和倾听另一个Bean的行为。SpringEvent对业务解耦真的很有用!1.自定义事件定义事件,继承自ApplicationEvent的类成为事件类;/***@authorStrive*@date2022/4/2218:00*@description*/@Data@ToStringpublicclassOrderProductEventextendsApplicationEvent{/**此类事件携带的信息*/privateStringorderId;publicOrderProductEvent(Objectsource,StringorderId){super(source);this.orderId=orderId;}}2.定义一个监听器来监听和处理事件,实现ApplicationListener接口或者使用@EventListener注解;/***实现ApplicationListener接口并指定监听的事件类型**@authorStrive*@date2022/4/2409:09*@description*/@Slf4j@ComponentpublicclassOrderProductListenerimplementsApplicationListener{/**使用onApplicationEvent方法接收和处理消息*/@SneakyThrows@OverridepublicvoidonApplicationEvent(OrderProductEventevent){StringorderId=event.getOrderId();长启动=System.currentTimeMillis();线程睡眠(2000);长端=System.currentTimeMillis();log.info("{}:验证订单商品价格所用时间:({})毫秒",orderId,(end-start));}}3。定义发布事件的发布者,通过ApplicationEventPublisher发布事件;推荐个人知识总结网站:www.java-family.cn/***@authorStrive*@date2022/4/2409:25*@description*/@Slf4j@Service@RequiredArgsConstructorpublicclassOrderService{/**注入ApplicationContext发布事件*/privatefinalApplicationContextapplicationContext;/***订单**@paramorderId订单ID*/publicStringbuyOrder(StringorderId){longstart=System.currentTimeMillis();//1.查询订单详情//2.查看订单价格(同步处理)applicationContext.publishEvent(newOrderProductEvent(this,orderId));//3.短信通知(异步处理)longend=System.currentTimeMillis();log.info("所有任务完成,总耗时:({})毫秒",end-start);return"购买成功";}}4。单个测试执行@SpringBootTestpublicclassOrderServiceTest{@AutowiredprivateOrderServiceorderService;@TestpublicvoidbuyOrderTest(){orderService.buyOrder("732171109");}}执行结果如下:2022-04-2410:13:17.535INFO44272---[main]c.c.m.e.listener.OrderProductListener:732171109:验证订单商品价格耗时:(2008)毫秒2022-04-2410:13:17.536信息44272---[主要]c.c.mingyue.event.service.OrderService:全部任务完成,总耗时:(2009)毫秒SpringEvent异步使用有些业务场景不需要在一次请求中同步完成,比如邮件发送,短信发送等.1、自定义事件@Data@AllArgsConstructorpublicclassMsgEvent{/**该类事件携带的信息*/publicStringorderId;}2、建议使用@EventListener注解定义监听器;@Slf4j@ComponentpublicclassMsgListener{@SneakyThrows@EventListener(MsgEvent.class)publicvoidsendMsg(MsgEventevent){StringorderId=event.getOrderId();长启动=System.currentTimeMillis();log.info("开发发送短信");log.info("开发发送邮件");线程.睡眠(4000);长端=System.currentTimeMillis();log.info("{}:发送短信和邮件所用时间:({})毫秒",orderId,(end-start));}}3。Definepublisher/***order*@paramorderIdorderID*/publicStringbuyOrder(StringorderId){longstart=System.currentTimeMillis();//1.查询订单详情//2.查看订单价格(同步处理)applicationContext.publishEvent(newOrderProductEvent(this,orderId));//3.短信通知(异步处理)applicationContext.publishEvent(newMsgEvent(orderId));长端=System.currentTimeMillis();log.info("所有任务完成,总耗时:({})毫秒",end-start);返回“购买成功”;}4。单个测试执行(同步)@TestpublicvoidbuyOrderTest(){orderService.buyOrder("732171109");}执行结果如下:2022-04-2410:24:13.905INFO54848---[main]c.c.m.e.listener.OrderProductListener:732171109:检查订单产品价格经过时间:(2004)毫秒2022-04-2410:24:13.906INFO54848---[main]c.c.mingyue.event.listener.MsgListener:developmentsendSMS2022-04-2410:24:13.907INFO54848---[main]c.c.mingyue.event.listener.MsgListener:开发发送邮件2022-04-2410:24:17.908INFO54848---[main]c.c.mingyue.event.listener.MsgListener:732171109:发送短信、邮件耗时:(4002)毫秒2022-04-2410:24:17.908INFO54848---[main]c.c.mingyue.event.service.OrderService:所有任务完成,总耗时:(6008)毫秒5.启用异步在启动类中添加@EnableAsync注解;@EnableAsync@SpringBootApplicationpublicclassMingYueSpringbootEventApplication{publicstaticvoidmain(String[]args){SpringApplication.run(MingYueSpringbootEventApplication.class,args);}}Listener类需要开启异步方法,添加@Async注解;@Async@SneakyThrows@EventListener(MsgEvent.class)publicvoidsendMsg(MsgEventevent){StringorderId=event.getOrderId();长启动=System.currentTimeMillis();log.info("开发发送短信");log.info("开发发送邮件");线程.睡眠(4000);长端=System.currentTimeMillis();log.info("{}:发送短信和邮件的时间:({})毫秒",orderId,(end-start));}6.单测执行(异步)发送短信的线程显示task-1、主线程结束后(总时间:(2017)毫秒),控制台停止打印;2022-04-2410:30:59.002INFO59448---[main]c.c.m.e.listener.OrderProductListener:732171109:验证订单产品价格耗时:(2009)毫秒2022-04-2410:30:59.009INFO59448---[main]c.c.mingyue.event.service.OrderService:所有任务完成,总耗时:(2017)毫秒2022-04-2410:30:59.028INFO59448---[task-1]c.c.mingyue.event.listener.MsgListener:开发发送短信2022-04-2410:30:59.028INFO59448---[task-1]c.c.mingyue.event.listener.MsgListener