现在市面上流行的很多消息中间件就是采用的该种模式,这种模式 在实际业务中 将 事件发布者(Publisher) 与 事件订阅者 (Subscriber)通过额外的事件通道(Event Channel)来解耦,其基本原理与先前提到的观察者模式有些许类似,但发布订阅模式额外存在了Event Channel的概念,也因此解决了 主题(Subject)和 Observer(观察者)...
ApplicationEventPublisher是spring提供的一个事件发布器使用它可以实现发布订阅模式, 下面在spring环境中实现下上边的例子. bankService publicclassBankAccountService{//注入事件发布器@AutowiredprivateApplicationEventPublisher applicationEventPublisher;publicvoidtransfer(){ System.out.println("发起转账");// 参数是需要...
private final ApplicationEventPublisher publisher; public void goHome() { publisher.publishEvent(new OpenDoorEvent("open door", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))); } } Event 这个就简单了,任何类型都可以。例如我自定义一个开门的事件类 @RequiredArgsConstructor @Getter pub...
@RestController@RequestMapping("/user")@Slf4jpublicclassUserController{@AutowiredprivateApplicationEventPublisherpublisher;@GetMapping("/register")publicvoidregister(Stringname,intage){Useruser=User.builder().name(name).age(age).build();// 事件发布publisher.publishEvent(newUserRegisterEvent(user));log.info...
applicationContext.publishEvent(new ApplicationEvent(new String(“我发布的时间”)) {}); AbstractApplicationContext#publishEvent this.getApplicationEventMulticaster().multicastEvent((ApplicationEvent)applicationEvent, eventType); 如果发现有任务执行器,就交给它处理,没有的话就直接处理。默认情况下是没有的 ...
context.start(); // ContextStartedEvent // 停止 Spring 上下文 context.stop(); // ContextStoppedEvent // 关闭 Spring 应用上下文 context.close(); // ContextClosedEvent } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { ...
String s = event.getObject().toString(); System.out.println("结束做事"+s); } } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 事件发送 @Component public class DemoEventPublisher { @Autowired
如下所示,楼主定义的Event类叫做UserActionEvent。 EnumUserOperate 枚举类 三、事件类定义好了,我们去定义操作发布:ApplicationEventPublisher,快点跟上别掉队了。 我是在UserServiceImpl中进行事件发布的,如下: 发布者会调用 ApplicationEventPublisher的publishEvent 方法对某一事件进行发布。随后Spring容器会把该事件告诉所...
Spring 事件发布 ApplicationEventPublisher 背景 项目中正好用到了这注解,就是当新来用户好友的时候进行匹配,这个时候就是发布一个匹配事件到队列中,定义一个线程池进行从队列中拉取匹配事件进行处理 还有就是开源的中间件中也会用到大量的监听器机制,比如Nacos源码中就有这种事件的发布和订阅机制,比如配置中心配置改变...
事件源(ApplicationEvent):这个就是你要发布的事件对象。 事件发布器(ApplicationEventPublisher):这是事件的发布工具。 事件监听器(ApplicationListener):这个相当于是事件的消费者。 以上三个要素,事件源和事件监听器都可以有多个,事件发布器(通常是由容器来扮演)一般来说只有一个。