一。概述
使用场景:用户注册完成时,需要给该用户发送邮件、发送优惠劵等等操作,实现业务的解耦(MQ的异步 销峰 解耦)
大体步骤
1.UserService 在完成自身的用户注册逻辑之后,仅仅只需要发布一个 UserRegisterEvent 事件,而无需关注其它拓展逻辑。
2.其它 Service 可以自己订阅 UserRegisterEvent 事件,实现自定义的拓展逻辑
友情提示:很多时候,我们会把观察者模式和发布订阅模式放在一起对比
简单来说,发布订阅模式属于广义上的观察者模式,在观察者模式的 Subject 和 Observer 的基础上,引入 Event Channel 这个中介,进一步解耦
二。Spring 事件机制
Spring 基于观察者模式,实现了自身的事件机制,由三部分组成
a.事件发布者 实现ApplicationEventPublisherAware 对应上面的UserService
b.事件 继承ApplicationEvent 对应上面的UserRegisterEvent
c.事件监听器 ApplicationListener 实现ApplicationListener<UserRegisterEvent> 对应上面的其他Service
友情提示:JDK 也内置了事件机制的实现,考虑到通用性,Spring 的事件机制是基于它之上进行拓展。
ApplicationEvent 继承自 java.util.EventObject
ApplicationListener 继承自 java.util.EventListener
我们写的代码是继承spring的 ApplicationEventPublisherAware
ApplicationEvent
ApplicationListener
三。代码案例
1.事件类
2.事件发布者
3.事件监听者
1.事件类
public class UserRegisterEvent extends ApplicationEvent {
private String username;
public UserRegisterEvent(Object source) {
super(source);
}
public UserRegisterEvent(Object source, String username) {
super(source);
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
2.事件发布者
@Service
public class UserService implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
public void registerUser(String username) {
System.out.println("用户表添加一个用户");
applicationEventPublisher.publishEvent(new UserRegisterEvent(this, username));
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
3.事件监听器
@Service
public class CouponService implements ApplicationListener<UserRegisterEvent> {
@Override
public void onApplicationEvent(UserRegisterEvent userRegisterEvent) {
System.out.println("优惠券监听到用户注册事件");
}
}
@Service
public class EmailService implements ApplicationListener<UserRegisterEvent> {
@Override
public void onApplicationEvent(UserRegisterEvent userRegisterEvent) {
System.out.println("邮箱监听到用户注册事件");
}
}