基于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 ...
随机推荐
- 音视频开发进阶——YUV与RGB的采样与存储格式
在上一篇文章中,我们带大家了解了视频.图像.像素和色彩之间的关系,还初步认识了两种常用的色彩空间,分别是大家比较熟悉的 RGB,以及更受视频领域青睐的 YUV.今天,我们将继续深入学习 RGB.YUV ...
- modulemap的使用方法
modulemap的作用 modulemap 文件是用来解决 C,Object-C,C++ 代码在 Swift 项目中集成的问题的. 在 Swift 项目中,如果需要使用 C,Object-C 或 ...
- C语言指针--指针中的const
文章目录 前言 一.const 1.什么是const 2.const的使用 二.const修饰一级指针 1.const放在 `*` 左边 2.const在`*`右边 三.const修饰二级指针 1.c ...
- 【Dotnet 工具箱】推荐一个使用 C# 开发的轻量级压测工具
你好,这里是 Dotnet 工具箱,定期分享 Dotnet 有趣,实用的工具和组件,希望对您有用! 轻量级压测工具 LoadTestToolbox 是一个使用 C# 开发的轻量级压测工具,基于 .NE ...
- Centos7中Jar快速启动脚本
Centos7中Jar快速启动脚本 创建一个文本,将以下脚本内容复制到文本当中,重命名文本后缀为.sh 注意:根据自己的项目进行更改相关内容,对应注释已说明 #!/bin/sh APP_NAME=ma ...
- Swithch反汇编(四种)
------------恢复内容开始------------ Switch语法格式 Switch(表达式) { case 常量表达式1: 语句; break; case 常量表达式2: 语句; bre ...
- 基于C#的无边框窗体动画效果的完美解决方案 - 开源研究系列文章
最近在整理和编写基于C#的WinForm应用程序,然后碰到一个其他读者也可能碰到的问题,就是C#的Borderless无边框窗体的动画效果问题. 在Visual Studio 2022里,C#的Win ...
- TCP超时分析
参考链接: Linux 建立 TCP 连接的超时时间分析 Linux 建立 TCP 连接的超时时间分析 Linux 系统默认的建立 TCP 连接的超时时间为 127 秒. 2 分 7 秒即 127 秒 ...
- Power AutoMate: 运行脚本程序
运行脚本文件 操作步骤 配置脚本 点击脚本文件菜单,选中运行python脚本.在其中输入需要徐行的脚本点击保存 之后界面会如下所示: 运行程式 可以看到程式正常运行
- enumerate()使用方法
enumerate()(单词意思是枚举的意思)是python中的内置函数, enumerate(X,[start=0]) 函数中的参数X可以是一个迭代器(iterator)或者是一个序列, start ...