基于Spring事件驱动模式实现业务解耦
事件驱动模式
举个例子
大部分软件或者APP都有会有会员系统,当我们注册为会员时,商家一般会把我们拉入会员群、给我们发优惠券、推送欢迎语什么的。

值得注意的是:
- 注册成功后才会产生后面的这些动作;
- 注册成功后的这些动作没有先后执行顺序之分;
- 注册成功后的这些动作的执行结果不能互相影响;
传统写法
public Boolean doRegisterVip(){
//1、注册会员
registerVip();
//2、入会员群
joinMembershipGroup();
//3、发优惠券
issueCoupons();
//4、推送消息
sendWelcomeMsg();
}
这样的写法将所有的动作都耦合在doRegisterVip方法中,首先执行效率低下,其次耦合度太高,最后不好扩展。那么如何优化这种逻辑呢?
事件驱动模式原理介绍
Spring的事件驱动模型由三部分组成:
事件:用户可自定义事件类和相关属性及行为来表述事件特征,Spring4.2之后定义事件不需要再显式继承ApplicationEvent类,直接定义一个bean即可,Spring会自动通过PayloadApplicationEvent来包装事件。
事件发布者:在Spring中可通过ApplicationEventPublisher把事件发布出去,这样事件内容就可以被监听者消费处理。
事件监听者:ApplicationListener,监听发布事件,处理事件发生之后的后续操作。
原理图如下:

代码实现
1. 定义基本元素
事件发布者:EventEngine.java、EventEngineImpl.java
package com.example.event.config;
/**
* 事件引擎
*/
public interface EventEngine {
/**
* 发送事件
*
* @param event 事件
*/
void publishEvent(BizEvent event);
}
package com.example.event.config;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import org.springframework.util.CollectionUtils;
/**
* 事件引擎实现类
*/
public class EventEngineImpl implements EventEngine {
/**
* 异步执行器。也系统需要自行定义线程池
*/
private Executor bizListenerExecutor;
/**
* 是否异步,默认为false
*/
private boolean async;
/**
* 订阅端 KEY是TOPIC,VALUES是监听器集合
*/
private Map<String, List<BizEventListener>> bizSubscribers = new HashMap<>(16);
@Override
public void publishEvent(BizEvent event) {
List<BizEventListener> listeners = bizSubscribers.get(event.getTopic());
if (CollectionUtils.isEmpty(listeners)) {
return;
}
for (BizEventListener bizEventListener : listeners) {
if (bizEventListener.decide(event)) {
//异步执行的话,放入线程池
if (async) {
bizListenerExecutor.execute(new EventSubscriber(bizEventListener, event));
} else {
bizEventListener.onEvent(event);
}
}
}
}
/**
* Setter method for property <tt>bizListenerExecutor</tt>.
*
* @param bizListenerExecutor value to be assigned to property bizListenerExecutor
*/
public void setBizListenerExecutor(Executor bizListenerExecutor) {
this.bizListenerExecutor = bizListenerExecutor;
}
/**
* Setter method for property <tt>bizSubscribers</tt>.
*
* @param bizSubscribers value to be assigned to property bizSubscribers
*/
public void setBizSubscribers(Map<String, List<BizEventListener>> bizSubscribers) {
this.bizSubscribers = bizSubscribers;
}
/**
* Setter method for property <tt>async</tt>.
*
* @param async value to be assigned to property async
*/
public void setAsync(boolean async) {
this.async = async;
}
}
事件:BizEvent.java
package com.example.event.config;
import java.util.EventObject;
/**
* 业务事件
*/
public class BizEvent extends EventObject {
/**
* Topic
*/
private final String topic;
/**
* 业务id
*/
private final String bizId;
/**
* 数据
*/
private final Object data;
/**
* @param topic 事件topic,用于区分事件类型
* @param bizId 业务ID,标识这一次的调用
* @param data 事件传输对象
*/
public BizEvent(String topic, String bizId, Object data) {
super(data);
this.topic = topic;
this.bizId = bizId;
this.data = data;
}
/**
* Getter method for property <tt>topic</tt>.
*
* @return property value of topic
*/
public String getTopic() {
return topic;
}
/**
* Getter method for property <tt>id</tt>.
*
* @return property value of id
*/
public String getBizId() {
return bizId;
}
/**
* Getter method for property <tt>data</tt>.
*
* @return property value of data
*/
public Object getData() {
return data;
}
}
事件监听者:EventSubscriber.java
package com.example.event.config;
/**
* 事件监听者。注意:此时已经没有线程上下文,如果需要请修改构造函数,显示复制上下文信息
*/
public class EventSubscriber implements Runnable {
/**
* 业务监听器
**/
private BizEventListener bizEventListener;
/**
* 业务事件
*/
private BizEvent bizEvent;
/**
* @param bizEventListener 事件监听者
* @param bizEvent 事件
*/
public EventSubscriber(BizEventListener bizEventListener, BizEvent bizEvent) {
super();
this.bizEventListener = bizEventListener;
this.bizEvent = bizEvent;
}
@Override
public void run() {
bizEventListener.onEvent(bizEvent);
}
}
2. 其他组件
业务事件监听器:BizEventListener.java
package com.example.event.config;
import java.util.EventListener;
/**
* 业务事件监听器
*
*/
public interface BizEventListener extends EventListener {
/**
* 是否执行事件
*
* @param event 事件
* @return
*/
public boolean decide(BizEvent event);
/**
* 执行事件
*
* @param event 事件
*/
public void onEvent(BizEvent event);
}
事件引擎topic:EventEngineTopic.java
package com.example.event.config;
/**
* 事件引擎topic,用于区分事件类型
*/
public class EventEngineTopic {
/**
* 入会员群
*/
public static final String JOIN_MEMBERSHIP_GROUP = "joinMembershipGroup";
/**
* 发优惠券
*/
public static final String ISSUE_COUPONS = "issueCoupons";
/**
* 推送消息
*/
public static final String SEND_WELCOME_MSG = "sendWelcomeMsg";
}
3. 监听器实现
优惠券处理器:CouponsHandlerListener.java
package com.example.event.listener;
import com.example.event.config.BizEvent;
import com.example.event.config.BizEventListener;
import org.springframework.stereotype.Component;
/**
* 优惠券处理器
*/
@Component
public class CouponsHandlerListener implements BizEventListener {
@Override
public boolean decide(BizEvent event) {
return true;
}
@Override
public void onEvent(BizEvent event) {
System.out.println("优惠券处理器:十折优惠券已发放");
}
}
会员群处理器:MembershipHandlerListener.java
package com.example.event.listener;
import com.example.event.config.BizEvent;
import com.example.event.config.BizEventListener;
import org.springframework.stereotype.Component;
/**
* 会员群处理器
*/
@Component
public class MembershipHandlerListener implements BizEventListener {
@Override
public boolean decide(BizEvent event) {
return true;
}
@Override
public void onEvent(BizEvent event) {
System.out.println("会员群处理器:您已成功加入会员群");
}
}
消息推送处理器:MsgHandlerListener.java
package com.example.event.listener;
import com.example.event.config.BizEvent;
import com.example.event.config.BizEventListener;
import org.springframework.stereotype.Component;
/**
* 消息推送处理器
*/
@Component
public class MsgHandlerListener implements BizEventListener {
@Override
public boolean decide(BizEvent event) {
return true;
}
@Override
public void onEvent(BizEvent event) {
System.out.println("消息推送处理器:欢迎成为会员!!!");
}
}
事件驱动引擎配置:EventEngineConfig.java
package com.example.event.listener;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.example.event.config.BizEventListener;
import com.example.event.config.EventEngine;
import com.example.event.config.EventEngineImpl;
import com.example.event.config.EventEngineTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
/**
* 事件驱动引擎配置
*/
@Configuration
public class EventEngineConfig {
/**
* 线程池异步处理事件
*/
private static final Executor EXECUTOR = new ThreadPoolExecutor(20, 50, 10, TimeUnit.MINUTES,
new LinkedBlockingQueue(500), new CustomizableThreadFactory("EVENT_ENGINE_POOL"));
@Bean("eventEngineJob")
public EventEngine initJobEngine(CouponsHandlerListener couponsHandlerListener,
MembershipHandlerListener membershipHandlerListener,
MsgHandlerListener msgHandlerListener) {
Map<String, List<BizEventListener>> bizEvenListenerMap = new HashMap<>();
//注册优惠券事件
bizEvenListenerMap.put(EventEngineTopic.ISSUE_COUPONS, Arrays.asList(couponsHandlerListener));
//注册会员群事件
bizEvenListenerMap.put(EventEngineTopic.JOIN_MEMBERSHIP_GROUP, Arrays.asList(membershipHandlerListener));
//注册消息推送事件
bizEvenListenerMap.put(EventEngineTopic.SEND_WELCOME_MSG, Arrays.asList(msgHandlerListener));
EventEngineImpl eventEngine = new EventEngineImpl();
eventEngine.setBizSubscribers(bizEvenListenerMap);
eventEngine.setAsync(true);
eventEngine.setBizListenerExecutor(EXECUTOR);
return eventEngine;
}
}
4. 测试类
TestController.java
package com.example.event.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import com.example.event.config.BizEvent;
import com.example.event.config.EventEngine;
import com.example.event.config.EventEngineTopic;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 测试
*/
@RestController
@RequestMapping("/test")
public class TestController {
@Resource(name = "eventEngineJob")
private EventEngine eventEngine;
@GetMapping("/doRegisterVip")
public String doRegisterVip(@RequestParam(required = true) String userName,
@RequestParam(required = true) Integer age) {
Map<String, Object> paramMap = new HashMap<>(16);
paramMap.put("userName", userName);
paramMap.put("age", age);
//1、注册会员,这里不实现了
System.out.println("注册会员成功");
//2、入会员群
eventEngine.publishEvent(
new BizEvent(EventEngineTopic.JOIN_MEMBERSHIP_GROUP, UUID.randomUUID().toString(), paramMap));
//3、发优惠券
eventEngine.publishEvent(
new BizEvent(EventEngineTopic.ISSUE_COUPONS, UUID.randomUUID().toString(), paramMap));
//4、推送消息
eventEngine.publishEvent(
new BizEvent(EventEngineTopic.SEND_WELCOME_MSG, UUID.randomUUID().toString(), paramMap));
return "注册会员成功";
}
}
项目代码结构

调用接口
http://localhost:8080/test/doRegisterVip?userName=zhangsan&age=28

基于Spring事件驱动模式实现业务解耦的更多相关文章
- 基于Spring的发布订阅模式 EventListener
基于Spring的发布订阅模式 在我们使用spring开发应用时,经常会碰到要去解耦合一些依赖调用,比如我们在做代码的发布流程中,需要去通知相关的测试,开发人员关注发布中的错误信息.而且通知这个操作又 ...
- Spring中如何使用工厂模式实现程序解耦?
目录 1. 啥是耦合.解耦? 2. jdbc程序进行解耦 3.传统dao.service.controller的程序耦合性 4.使用工厂模式实现解耦 5.工厂模式改进 6.结语 @ 1. 啥是耦合.解 ...
- 基于Spring实现策略模式
背景: 看多很多策略模式,总结下来实现原理大体都差不多,在这里主要是讲解下自己基于Spring更优雅的实现方案:这个方案主要是看了一些开源rpc和Spring相关源码后的一些思路,所以在此进行总结 首 ...
- 我的自定义框架 || 基于Spring Boot || 第一步
今天在园子里面看到一位大神写的springboot做的框架,感觉挺不错,遂想起来自己还没有一个属于自己的框架,决定先将大神做好的拿过来,然后加入自己觉得需要的模块,不断完善 目前直接复制粘贴过来的,后 ...
- 干货|基于 Spring Cloud 的微服务落地
转自 微服务架构模式的核心在于如何识别服务的边界,设计出合理的微服务.但如果要将微服务架构运用到生产项目上,并且能够发挥该架构模式的重要作用,则需要微服务框架的支持. 在Java生态圈,目前使用较多的 ...
- 基于Spring Cloud的微服务落地
微服务架构模式的核心在于如何识别服务的边界,设计出合理的微服务.但如果要将微服务架构运用到生产项目上,并且能够发挥该架构模式的重要作用,则需要微服务框架的支持. 在Java生态圈,目前使用较多的微服务 ...
- Spring实战5:基于Spring构建Web应用
主要内容 将web请求映射到Spring控制器 绑定form参数 验证表单提交的参数 对于很多Java程序员来说,他们的主要工作就是开发Web应用,如果你也在做这样的工作,那么你一定会了解到构建这类系 ...
- Spring mvc 模式小结
http://www.taobaotesting.com/blogs/2375 1.spring mvc简介 Spring MVC框架是一个MVC框架,通过实现Model-View-Controlle ...
- 基于Spring的Web缓存
缓存的基本思想其实是以空间换时间.我们知道,IO的读写速度相对内存来说是非常比较慢的,通常一个web应用的瓶颈就出现在磁盘IO的读写上.那么,如果我们在内存中建立一个存储区,将数据缓存起来,当浏览器端 ...
- 基于Spring Cloud和Netflix OSS 构建微服务-Part 1
前一篇文章<微服务操作模型>中,我们定义了微服务使用的操作模型.这篇文章中,我们将开始使用Spring Cloud和Netflix OSS实现这一模型,包含核心部分:服务发现(Servic ...
随机推荐
- 一分钟学一个 Linux 命令 - find 和 grep
前言 大家好,我是 god23bin.欢迎来到<一分钟学一个 Linux 命令>系列,每天只需一分钟,记住一个 Linux 命令不成问题.今天需要你花两分钟时间来学习下,因为今天要介绍的是 ...
- 【QCustomPlot】绘制 x-y 曲线图
说明 使用 QCustomPlot 绘图库辅助开发时整理的学习笔记.同系列文章目录可见 <绘图库 QCustomPlot 学习笔记>目录.本篇介绍如何使用 QCustomPlot 绘制 x ...
- Dash应用页面整体布局技巧
本文示例代码已上传至我的Github仓库:https://github.com/CNFeffery/dash-master 大家好我是费老师,对于刚上手dash应用开发的新手朋友来说,如何进行合理且美 ...
- linux 服务器上查看日志的几种方式
1.tail命令:tail -f filename 可以动态的查看日志的输出内容. 查看文件的最后几行,默认是10行,但是可以通过-n 参数来指定要查看的行数. 例如tail -n ...
- 【原创】C++中vector的remove()函数
话不多说,直接来 remove()干了什么: 把要删除元素后面的值移动到前面,返回最后一个被改变值的下一个迭代器. 举栗: // 首先,定义一个vector vector<int> dem ...
- 力扣 662 https://leetcode.cn/problems/maximum-width-of-binary-tree/
需要了解树的顺序存储 如果是普通的二叉树 ,底层是用链表去连接的 如果是满二叉树,底层用的是数组去放的,而数组放的时候 会有索引对应 当前父节点是索引i,下一个左右节点就是2i,2i+1 利用满二叉树 ...
- 如何将Maven项目快速改造成一个java web项目(方式二)
原始的maven项目,使用IDEA打开后,目录结构如下所示 删除pom.xml文件,删除resource目录,将java目录下的代码放到项目根目录下, 将webapp目录放到项目根目录下.如下图所示 ...
- 使用Canal同步mysql数据到es
一.简介 Canal主要用途是基于 MySQL 数据库增量日志解析,提供增量数据订阅和消费. 当前的 canal 支持源端 MySQL 版本包括 5.1.x , 5.5.x , 5.6.x , 5.7 ...
- Windows安装SSH服务器
1.打开Win的设置并在设置中找到应用 2.在应用中依次选择应用和功能 可选功能 3.在可选功能中选择添加功能 (OpenSSH客户端默认已存在) 选中OpenSSH服务器后点击下方的安装 4.快捷键 ...
- Llama 2 来袭 - 在 Hugging Face 上玩转它
引言 今天,Meta 发布了 Llama 2,其包含了一系列最先进的开放大语言模型,我们很高兴能够将其全面集成入 Hugging Face,并全力支持其发布. Llama 2 的社区许可证相当宽松,且 ...