ApplicationEventPublisher 异步解耦

需求

当用户注册后,给他发送一封邮件通知他注册成功了,然后给他初始化积分,再发放一张新用户注册优惠券等。

用户注册事件

public class UserRegisterEvent extends ApplicationEvent{
    public UserRegisterEvent(String name) { //name即source 复杂的对象,但注意要了解清楚序列化机制
        super(name);
    }
}

用户注册服务发布者

@Service
public class UserService  {
	
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void register(String name) {
        System.out.println("用户:" + name + " 已注册!");
        applicationEventPublisher.publishEvent(new UserRegisterEvent(name));
    }
}

注意:再Spring中,服务必须交给 Spring 容器托管。ApplicationEventPublisherAware 是由 Spring 提供的用于为 Service 注入 ApplicationEventPublisher 事件发布器的接口,使用这个接口,我们自己的 Service 就拥有了发布事件的能力。用户注册后,不再是显示调用其他的业务 Service,而是发布一个用户注册事件。

创建事件订阅者(邮件服务、积分服务等)

@Service
public class EmailService implements ApplicationListener<UserRegisterEvent> {
    @Override
    public void onApplicationEvent(UserRegisterEvent userRegisterEvent) {
        System.out.println("邮件服务接到通知,给 " + userRegisterEvent.getSource() + " 发送邮件...");
    }
}

注意:事件订阅者的服务同样需要托管于 Spring 容器,ApplicationListener接口是由 Spring 提供的事件订阅者必须实现的接口,我们一般把该 Service 关心的事件类型作为泛型传入。处理事件,通过 event.getSource() 即可拿到事件的具体内容,在本例中便是用户的姓名。

SpringBoot 测试启动类

@SpringBootApplication
@RestController
public class EventDemoApp {
    public static void main(String[] args) {
        SpringApplication.run(EventDemoApp.class, args);
    }
    @Autowired
    UserService userService;
    @RequestMapping("/register")
    public String register(){
        userService.register("zhangsan");
        return "success";
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring ApplicationEventPublisher 是 Spring 框架中的一个接口,用于发布应用程序的事件。通过 ApplicationEventPublisher,我们可以在应用程序中定义和发布自定义事件,并将其传播到对该事件感兴趣的监听器。 Spring 框架基于观察者设计模式,通过 ApplicationEventPublisherApplicationListener 来实现事件发布和监听。当我们需要在应用程序中触发一些事件时,可以创建一个实现了 ApplicationEvent 类的自定义事件,并使用 ApplicationEventPublisher 将该事件发布出去。 使用 ApplicationEventPublisher 的方式有两种: 1. 通过实现 ApplicationEventPublisherAware 接口自动注入 ApplicationEventPublisher 实例。这样就可以在任何需要发布事件的地方直接调用 ApplicationEventPublisherpublishEvent 方法。 2. 在 Spring 容器中注入 ApplicationEventPublisher 实例,然后在需要发布事件的地方手动调用 publishEvent 方法。 发布事件之后,事件会被传播给所有实现了 ApplicationListener 接口的监听器。通过实现 ApplicationListener 接口,我们可以自定义事件的监听器,并在监听器中编写逻辑,处理事件触发后的业务逻辑。 Spring 框架的事件机制可以使我们的应用程序更加模块化和可扩展。我们可以定义多个事件和监听器,实现不同模块之间的解耦。同时,通过事件机制,我们也可以更方便地实现日志记录、业务流程控制等功能。 总之,Spring ApplicationEventPublisher 是 Spring 框架中的一个重要组件,用于实现事件发布和监听。通过定义自定义事件和监听器,我们可以实现应用程序的模块化和解耦,提高代码的可维护性和可扩展性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值