developS

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

观察者模式在项目中的实际应用

观察者模式观察者模式的定义:在对象之间定义一个一对多的依赖,当一个对象状态改变的时候,所有依赖的对象都会自动收到通知!

发布订阅模式是什么?

观察者模式和发布订阅模式是有一点点区别的,区别有以下几点:

  • 前者:观察者订阅主题,主题也维护观察者的记录,而后者:发布者和订阅者不需要彼此了解,而是在消息队列或代理的帮助下通信,实现松耦合。
  • 前者主要以同步方式实现,即某个事件发生时,由Subject调用所有Observers的对应方法,后者则主要使用消息队列异步实现。

Spring事件监听机制概述

SpringBoot中事件监听机制则通过发布-订阅实现,主要包括以下三部分:

  • 事件 ApplicationEvent,继承JDK的EventObject,可自定义事件。
  • 事件发布者 ApplicationEventPublisher,负责事件发布。
  • 事件监听者 ApplicationListener,继承JDK的EventListener,负责监听指定的事件。

一个完整的事件,由事件源、事件发布、事件监听三部分组成
声明事件 public class SendEmailEvent extends ApplicationEvent {

解耦 异步的左右 直接调用接口也可实现 但是不能解耦
事件发布 new publish(new VeAccountNotifyEventnotifyEvent(this,version)) 发送邮件(指令)
事件监听 @EventListener(VeAccountNotifyEventnotifyEvent event) 消费者(发送邮件)

点击确认后 (调用服务接口) new 事件发布 new publish(new VeAccountNotifyCallBackEvent(this,version)) 发送邮件(指令)
事件监听 @EventListener(VeAccountNotifyCallBackEvent event) 消费者(发送邮件)

 

复制代码
//基于ApplicationEvent实public class VeAccountNotifyEvent extends ApplicationEvent 

private String version;
public VeAccountNotifyEvent(Object source, String version) {
        super(source);
        this.version = version;
    }

    public String getVersion() {
        return version;
    }
}

//定义发布者
@Service
public class EventPublisher {
    @Autowired
    private ApplicationContext context;

    public void publish(ApplicationEvent event) {
        context.publishEvent(event);
    }
}
//发布的触发时机
if(needSendConfirmEmail){
            eventPublisher.publish(new 
       VeAccountNotifyEvent(this,version));
}

//订阅者去发送 账号变动的邮件
public void process(VeAccountNotifyEvent event) {
        String version = event.getVersion();
        if (StringUtils.isBlank(version)) {
            return;
        }
   
    VeEmail.send("变更通知邮件", tempContent, Collections.singletonList(tempBase.getContactEmail()), "");
    }
}


//邮件中有链接  等待修改者确认机制
    @SneakyThrows
    public ConfirmAccountResponse confirm(String version) {
        if(StringUtils.isBlank(version)){
            return null;
        }switch (type){
case "3":

//修改者确认了 eventPublisher.publish(new VeAccountNotifyCallBackEvent(this,uid)); break; } return new ConfirmAccountResponse(); }

//订阅者 真正发送邮件 表示从A变为了B
@EventListener
public void process(VeAccountNotifyCallBackEvent event) {
String version = event.getVersion();
if (StringUtils.isBlank(version)) {
return;
}
log.info("[[title=VeAccountNotifyCallBackEvent]],version = {}", version);
VeEmail.send("银行账号变更通知邮件", tempContent, Collections.singletonList(tempBase.getContactEmail()), "");
}
复制代码

 

posted on   四十四次日落95  阅读(54)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!
点击右上角即可分享
微信分享提示