void publishEvent(Object event); } 例如 @RequiredArgsConstructor @Service public class EventService { private final ApplicationEventPublisher publisher; public void goHome() { publisher.publishEvent(new OpenDoorEvent("open door", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))); } }...
在需要更新user对象的地方,调用UserUpdatePublisher的publishEvent()方法。 示例代码如下: // UserUpdateEvent.javapublicclassUserUpdateEvent{privateUser user;publicUserUpdateEvent(User user){this.user = user;}publicUsergetUser(){returnuser;}}// UserUpdatePublisher.java@ComponentpublicclassUserUpdatePublisher{...
ApplicationContext.publishEvent 是Spring提供的解耦的一种方式 (基于内存)。同样可以使用 MQ 组件 / 线程池 代替。 参数类 NotifyEvent.java importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructorpublicclassNotifyEvent {/*** 这里放需要传递的...
1、定义事件继承ApplicationEvent /** * 订单完成事件 */@GetterpublicclassOrderFinishedEventextendsApplicationEvent{privatefinalOrderorder;publicOrderFinishedEvent(Objectsource,Orderorder){super(source);this.order=order;}} 2、发布事件 @ResourceprivateApplicationContextapplicationContext;applicationContext.publishEven...
在Spring Boot应用程序中,我们可以通过实现ApplicationEventPublisher接口来发布事件。以下是一个简单的示例,展示了如何在一个服务类中发布事件。 packagecom.example.demo.service;importcom.example.demo.event.CustomEvent;importorg.springframework.context.ApplicationEventPublisher;importorg.springframework.stereotype.Service...
SpringBoot:Event实现发布/订阅模式 不管是否基于spring boot 的发布订阅模型,最终都是开启了线程执行任务,和使用第三方的MQ消息组件,问题在于重启服务器或者未知原因崩溃的时候,消息的恢复机制要自行处理。 如图所示支付业务中,用户支付成功之后,后续还有很多的业务流程,但是对于用户来讲是透明的,所以为了提高接口的响应...
spring boot publishEvent 异步执行 在使用spring的时候,我们经常会用到application.publishEvent()的方式来达到解耦合的目的,但是spring默认配置是同步的方式调用,在spring boot中如果需要异步执行的,配置如下: package hello; import java.util.concurrent.Executor;...
public String publishMsg(String message){ //发布了一条信息:message System.out.println(message); return "OK"; } } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24.
发布者会调用 ApplicationEventPublisher的publishEvent 方法对某一事件进行发布。随后Spring容器会把该事件告诉所有的监听者(我的“女神”有动态了),监听者根据拿到的“信息、某些指令或者某些数据”去做一些业务上的操作。 这个模式常常会与设计模式中观察者模式进行对比。举个栗子:上课铃响了,老师和同学听到铃声后,都...
public void orderLog(PlaceOrderEvent event) { log.info("[afterPlaceOrder] log."); } } 当然,还需要开启异步,SpringBoot项目默认是没有开启异步的,我们需要手动配置开启异步功能,很简单,只需要在配置类上加上@EnableAsync注解就行了,这个注解用于声明启用Spring的异步方法执行功能,需要和@Configuration注解一起使...