1.背景
在设计模式中,观察者模式是一个常用的设计模式:
观察者模式是软件设计模式的一种。在此种模式中,一个目标对象管理所有相依于它的观察者对象,并且在它本身的状态改变时主动发出通知。这通常透过呼叫各观察者所提供的方法来实现。
此种模式通常被用来实时事件处理系统。
在我们日常业务开发中,观察者模式对我们很大的一个作用,在于实现业务的解耦。以用户注册的场景来举例子,假设在用户注册完成时,需要给该用户发送邮件、发送优惠劵等等操作,如下图所示:
- UserService 在完成自身的用户注册逻辑之后,仅仅只需要发布一个 UserRegisterEvent 事件,而无需关注其它拓展逻辑。
- 其它 Service 可以自己订阅 UserRegisterEvent 事件,实现自定义的拓展逻辑。
很多时候,我们会把观察者模式和发布订阅模式放在一起对比。
简单来说,发布订阅模式属于广义上的观察者模式,在观察者模式的 Subject 和 Observer 的基础上,引入 Event Channel 这个中介,进一步解耦。如下图所示:
2.Spring 事件机制
Spring 基于观察者模式,实现了自身的事件机制,由三部分组成:
- 事件 ApplicationEvent:通过继承它,实现自定义事件。另外,通过它的 source 属性可以获取事件源,timestamp 属性可以获得发生时间。
- 事件发布者 ApplicationEventPublisher:通过它,可以进行事件的发布。
- 事件监听器 ApplicationListener:通过实现它,进行指定类型的事件的监听。
JDK 也内置了事件机制的实现,考虑到通用性,Spring 的事件机制是基于它之上进行拓展。因此,ApplicationEvent 继承自 java.util.EventObject,ApplicationListener 继承自 java.util.EventListener
3. 入门示例
具体的场景还是以用户注册为例子,用户新建完成过后,分别给用户下发一张优惠券,以及给用户邮箱下发一封邮件。
3.1 引入依赖
在 pom.xml 文件中,引入相关依赖。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>lab-54-demo</artifactId>
<dependencies>
<!-- 实现对 Spring MVC 的自动化配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
引入 web 依赖是方别后续能提供 API 接口
3.2 UserRegisterEvent
创建 UserRegisterEvent 事件类,继承 ApplicationEvent 类,用户注册事件。代码如下:
/**
* @Description : 用户注册事件
* @Author : Jarvis
* @Date: 2021-03-29 10:18
*/
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;
}
}
通过在 UserRegisterEvent 类中,定义成员变量 userName,将用户名附带上。
(后续这个 usernName 作为用户信息会是连接优惠券和发邮件逻辑的桥梁)
3.3 UserService
创建 UserService 类
@Service
public class UserService implements ApplicationEventPublisherAware {//<1>
private Logger logger = LoggerFactory.getLogger(getClass());
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void register(String userName) {
//执行注册逻辑....
logger.info("[register][执行用户({})的注册逻辑]", userName);
//<2>. ......发布
applicationEventPublisher.publishEvent(new UserRegisterEvent(this, userName));
}
}
<1> 处,实现 ApplicationEventPublisherAware 接口,从而将 ApplicationEventPublisher 注入到其中。
<2> 处,在执行完注册逻辑后,调用 ApplicationEventPublisher 的 #publishEvent(ApplicationEvent event) 方法,发布「UserRegisterEvent」事件。
3.4 EmailService
创建 EmailService 类
@Service
public class EmailService implements ApplicationListener<UserRegisterEvent> { //<1>
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
@Async //<3>
public void onApplicationEvent(UserRegisterEvent event) { //<2>
logger.info("[onApplicationEvent][给用户({}) 发送邮件]", event.getUserName());
}
}
<1> 处,实现 ApplicationListener 接口,通过 E 泛型设置感兴趣的事件。
<2> 处,实现 #onApplicationEvent (E event)方法,针对监听的 UserRegisterEvent 事件,进行自定义处理。 可以不加 <3> 处,锦上添花,设置 @Async 注解,声明异步执行。毕竟实际场景下,发送邮件可能比较慢,又是非关键逻辑。
3.5 CouponService
创建 CouponService 类
@Service
public class CouponService {
private Logger logger = LoggerFactory.getLogger(getClass());
@EventListener // <1>
public void addCoupon(UserRegisterEvent event) {
logger.info("[addCoupon][给用户({}) 发放优惠劵]", event.getUserName());
}
}
<1> 处,在方法上,添加 @EventListener 注解,并设置监听的事件为 UserRegisterEvent。这是另一种监听的使用方式!
3.6 DemoController
@RestController
@RequestMapping("demo")
public class DemoController {
@Autowired
UserService userService;
@GetMapping("/register")
public String register(String userName) {
userService.register(userName);
throw new RuntimeException("异常");
}
}
3.8 简单测试
调用: http://127.0.0.1:8080/demo/register?userName=ABC 接口,进行注册。
日志结果:
4. Spring 内置事件
在 Spring 框架中,自定义了非常多的自定义事件,让我们更容易的进行拓展
- ContextStartedEvent:Spring Context 启动完成事件。
- ContextStoppedEvent:Spring Context 停止完成事件。
- ContextClosedEvent:Spring Context 停止开始事件。
- ContextRefreshedEvent:Spring Context 初始化或刷新完成事件。
也就是说,在 Spring Context 的整个生命周期中,会发布相应的 ApplicationContextEvent 事件。
SpringApplicationEvent 是 Spring Boot Application(应用)相关的事件基类,如下图所示: