当前位置: 首页 > news >正文

SpringBoot集成Redisson实现延迟队列

一、场景

1、下单未支付,超过10分钟取消订单

2、货到后7天未评价,自动好评

二、实现方案

1、使用xxl-job 定时任务按时检测,实时性不高

2、使用RabitMQ的插件rabbitmq_delayed_message_exchange插件

3、 redis的过期检测 redis.conf 中,加入一条配置notify-keyspace-events Ex开启过期监听

等等有很多方法,本文探索SpringBoot+Redisson实现该业务

三、代码

1、pom依赖

<!--        引入 redisson--><dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>3.15.4</version></dependency>

2、prop配置redis配置

spring:redis:host: 127.0.0.1port: 6379password: redisdatabase: 1timeout: 6000

3、创建RedissionConfig配置

config/RedissonConfig.java

package com.msb.crm.config;import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** 创建 RedissonConfig 配置* <p>* Created by fengqx*/
@Configuration
public class RedissonConfig {@Value("${spring.redis.host}")private String host;@Value("${spring.redis.port}")private int port;@Value("${spring.redis.database}")private int database;@Value("${spring.redis.password}")private String password;@Beanpublic RedissonClient redissonClient() {Config config = new Config();config.useSingleServer().setAddress("redis://" + host + ":" + port).setDatabase(database);
//                .setPassword(password);return Redisson.create(config);}
}

4、延迟队列工具类

utils/RedisDelayQueueUtil.java 与

utils/SpringUtil

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.util.Map;
import java.util.concurrent.TimeUnit;/*** 封装 Redis 延迟队列工具* <p>* Created by fengq*/
@Slf4j
@Component
public class RedisDelayQueueUtil {@Autowiredprivate RedissonClient redissonClient;/*** 添加延迟队列** @param t* @param delay* @param timeUnit* @param queueCode* @param <T>*/public <T> void addDelayQueue(T t, long delay, TimeUnit timeUnit, String queueCode) {try {RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueCode);RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);delayedQueue.offer(t, delay, timeUnit);log.info("添加延时队列成功,队列键:{},队列值:{},延迟时间:{}", queueCode, t, timeUnit.toSeconds(delay) + "秒");} catch (Exception e) {log.error("添加延时队列失败:{}", e.getMessage());throw new RuntimeException("添加延时队列失败");}}/*** 获取延迟队列** @param queueCode* @param <T>* @return* @throws InterruptedException*/public <T> T getDelayQueue(String queueCode) throws InterruptedException {RBlockingDeque<Map> blockingDeque = redissonClient.getBlockingDeque(queueCode);T value = (T) blockingDeque.take();return value;}
}
package com.msb.crm.util;import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;/*** SpringUtil 工具类* <p>* Created by fengq*/
@Slf4j
@Component
public class SpringUtil implements ApplicationContextAware {private static ApplicationContext applicationContext;/*** 服务器启动,Spring容器初始化时,当加载了当前类为bean组件后,将会调用下面方法注入ApplicationContext实例** @param applicationContext* @throws BeansException*/@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {log.info("applicationContext 初始化了");SpringUtil.applicationContext = applicationContext;}public static ApplicationContext getApplicationContext() {return applicationContext;}public static <T> T getBean(String beanId) {return (T) applicationContext.getBean(beanId);}public static <T> T getBean(Class<T> clazz) {return (T) applicationContext.getBean(clazz);}
}

5、业务枚举

/entity/RedisDelayQueue.java

/*** 延迟队列业务枚举* <p>* Created by fengq*/
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum RedisDelayQueue {ORDER_PAYMENT_TIMEOUT("ORDER_PAYMENT_TIMEOUT", "订单支付超时,自动取消订单", "orderPaymentTimeout"),ORDER_TIMEOUT_NOT_EVALUATED("ORDER_TIMEOUT_NOT_EVALUATED", "订单超时未评价,系统默认好评", "orderTimeoutNotEvaluated"),;/*** 延迟队列 Redis Key*/private String code;/*** 中文描述*/private String desc;/*** 延迟队列具体业务实现的 Bean* 可通过 Spring 的上下文获取*/private String beanId;
}

6、延迟对接执行器接口与执行器类

redis/RedisDelayQueueHandle.java 与 redis/RedisDelayQueueRunner.java

package com.msb.crm.redis;/*** 延迟队列执行器* <p>* Created by fenq*/
public interface RedisDelayQueueHandle<T> {void execute(T t);
}
package com.msb.crm.redis;import com.msb.crm.entity.RedisDelayQueue;
import com.msb.crm.util.RedisDelayQueueUtil;
import com.msb.crm.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;/*** 创建延迟队列消费线程* <p>* Created by fenq*/
@Slf4j
@Component
public class RedisDelayQueueRunner implements CommandLineRunner {@Autowiredprivate RedisDelayQueueUtil redisDelayQueueUtil;@Autowiredprivate SpringUtil springUtil;/*** 启动延迟队列** @param args*/@Overridepublic void run(String... args) {new Thread(() -> {while (true) {try {RedisDelayQueue[] queues = RedisDelayQueue.values();for (RedisDelayQueue queue : queues) {Object o = redisDelayQueueUtil.getDelayQueue(queue.getCode());if (null != o) {RedisDelayQueueHandle redisDelayQueueHandle = springUtil.getBean(queue.getBeanId());redisDelayQueueHandle.execute(o);}}} catch (InterruptedException e) {log.error("Redis延迟队列异常中断:{}", e.getMessage());}}}).start();log.info("Redis延迟队列启动成功");}
}

6、实现延迟业务-执行方法接口

  • OrderPaymentTimeout:订单支付超时延迟队列处理类
package com.msb.crm.redis;import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;import java.util.Map;/*** 订单支付超时处理* <p>* Created by fenq*/
@Slf4j
@Component
public class OrderPaymentTimeout implements RedisDelayQueueHandle<Map<String, Object>> {@Overridepublic void execute(Map<String, Object> map) {// TODO-MICHAEL: 2023-08-05 订单支付超时,自动取消订单处理业务...log.info("收到订单支付超时延迟消息:{}", map);}
}
  • OrderTimeoutNotEvaluated:订单超时未评价延迟队列处理类
package com.msb.crm.redis;import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;import java.util.Map;/*** 订单超时未评价处理* <p>* Created by fqngq*/
@Slf4j
@Component
public class OrderTimeoutNotEvaluated implements RedisDelayQueueHandle<Map<String, Object>> {@Overridepublic void execute(Map<String, Object> map) {// TODO-MICHAEL: 2023-08-05 订单超时未评价,系统默认好评处理业务...log.info("收到订单超时未评价延迟消息:{}", map);}
}

7、创建Controller方法

controller/RedisDelayQueueController.java

package com.msb.crm.controller;import com.msb.crm.entity.RedisDelayQueue;
import com.msb.crm.util.RedisDelayQueueUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;/*** 延迟队列测试* <p>* Created by fqngq*/
@RestController
@RequestMapping("/api/redis/delayQueue")
public class RedisDelayQueueController {@Autowiredprivate RedisDelayQueueUtil redisDelayQueueUtil;@GetMapping("/add")public void addQueue() {Map<String, Object> map1 = new HashMap<>();map1.put("orderId", "100");map1.put("remark", "订单支付超时,自动取消订单");Map<String, String> map2 = new HashMap<>();map2.put("orderId", "200");map2.put("remark", "订单超时未评价,系统默认好评");// 添加订单支付超时,自动取消订单延迟队列。为了测试效果,延迟30秒钟redisDelayQueueUtil.addDelayQueue(map1, 30, TimeUnit.SECONDS, RedisDelayQueue.ORDER_PAYMENT_TIMEOUT.getCode());// 订单超时未评价,系统默认好评。为了测试效果,延迟60秒钟redisDelayQueueUtil.addDelayQueue(map2, 60, TimeUnit.SECONDS, RedisDelayQueue.ORDER_TIMEOUT_NOT_EVALUATED.getCode());}
}

四、通过启动该接口,可以复现出延迟队列的执行逻辑

 本人还尝试了,添加队列,然后关闭应用。此时redis数据依旧保留

等一段时间(超过关闭时间)重启项目,此时也不会执行之前队列的数据,需要重新加入数据到队列,在消费新产生队列的后续可以消费到之前的内容(上次项目未执行完毕的)

此时可以打印出上次未执行完毕的数据,因此可以保证数据的最终一致性,可以有效在分布式应用中使用

相关文章:

SpringBoot集成Redisson实现延迟队列

一、场景 1、下单未支付&#xff0c;超过10分钟取消订单 2、货到后7天未评价&#xff0c;自动好评 二、实现方案 1、使用xxl-job 定时任务按时检测&#xff0c;实时性不高 2、使用RabitMQ的插件rabbitmq_delayed_message_exchange插件 3、 redis的过期检测 redis.conf 中…...

思想道德与法治

1【单选题】公民的基本权利是指宪法规定的公民享有的基本的、必不可少的权利。公民的基本权利有不同的类别&#xff0c;公民的通信自由和通信秘密属于 A、人身自由 B、经济社会权利 C、政治权利和自由 D、教育科学文化权利 您的答案&#xff1a;A 参考答案&#xff1a;A 查…...

vue3登录页面

使用了element-plus <template><div class"login-wrapper"><!-- 背景图或者视频 --><div class"background" style"width: 100%; height: 100%; position: absolute; top: 0px; left: 0px;overflow: hidden;z-index:50;&qu…...

SK5代理与IP代理:网络安全守护者的双重防线

一、IP代理与SK5代理简介 IP代理&#xff1a; IP代理是一种通过中间服务器转发网络请求的技术。客户端向代理服务器发出请求&#xff0c;代理服务器将请求转发至目标服务器&#xff0c;并将目标服务器的响应返回给客户端。IP代理的主要功能是隐藏用户的真实IP地址&#xff0c;提…...

线程间的同步、如何解决线程冲突与死锁

一、线程同步概念&#xff1a; 线程同步是指在多线程编程中&#xff0c;为了保证多个线程之间的数据访问和操作的有序性以及正确性&#xff0c;需要采取一些机制来协调它们的执行。在多线程环境下&#xff0c;由于线程之间是并发执行的&#xff0c;可能会出现竞争条件&#xf…...

8.4一日总结

1.远程仓库的提交方式(免密提交) a.ssh:隧道加密传输协议,一般用来登录远程服务器 b.使用 git clone 仓库名 配置(生成公私钥对) ssh-Keygen [-t rsa -C 邮箱地址] 通过执行上述命令,全程回车,就会在~/.ssh/id_rsa(私钥)和id_rsa.pub(公钥),私钥是必须要保存好的,并不能…...

【面试】某公司记录一次面试题

文章目录 框架类1. Spring boot与 spring 架相比&#xff0c;好在哪里?2. Spring boot以及 Spring MVC 常用注解(如requestingMapping&#xff0c;responseBody 等)3. 常用的java 设计模式&#xff0c;spring 中用到哪些设计模式4. SpringIOC是什么&#xff0c;如何理解5. AOP…...

215. 数组中的第K个最大元素(快排+大根堆+小根堆)

题目链接&#xff1a;力扣 解题思路&#xff1a; 方法一&#xff1a;基于快速排序 因为题目中只需要找到第k大的元素&#xff0c;而快速排序中&#xff0c;每一趟排序都可以确定一个最终元素的位置。 当使用快速排序对数组进行降序排序时&#xff0c;那么如果有一趟排序过程…...

Ubuntu18.04配置ZED_SDK 4.0, 安装Nvidia显卡驱动、cuda12.1

卸载错误的显卡驱动、cuda 首先卸载nvidia相关的、卸载cuda sudo apt-get purge nvidia* sudo apt-get autoremove sudo apt-get remove --auto remove nvidia-cuda-toolkit sudo apt-get purge nvidia-cuda-toolkit 官方卸载cuda的方法&#xff1a; sudo apt-get --purge re…...

张量Tensor 深度学习

1 张量的定义 张量tensor理论是数学的一个分支学科&#xff0c;在力学中有重要的应用。张量这一术语源于力学&#xff0c;最初是用来表示弹性介质中各点应力状态的&#xff0c;后来张量理论发展成为力学和物理学的一个有力数学工具。 张量&#xff08;Tensor&#xff09;是一个…...

用Rust实现23种设计模式之桥接模式

桥接模式的优点&#xff1a; 桥接模式的设计目标是将抽象部分和实现部分分离&#xff0c;使它们可以独立变化。这种分离有以下几个优点&#xff1a; 解耦和灵活性&#xff1a;桥接模式可以将抽象部分和实现部分解耦&#xff0c;使它们可以独立地变化。这样&#xff0c;对于抽象…...

扩散模型实战(一):基本原理介绍

扩散模型&#xff08;Diffusion Model&#xff09;是⼀类⼗分先进的基于物理热⼒学中的扩散思想的深度学习⽣成模型&#xff0c;主要包括前向扩散和反向扩散两个过程。⽣成模型除了扩散模型之外&#xff0c;还有出现较早的VAE&#xff08;Variational Auto-Encoder&#xff0c;…...

解决npm ERR! code ERESOLVE -npm ERR! ERESOLVE could not resolve

当使用一份vue源码开发项目时&#xff0c;npm install 报错了 npm ERR! code ERESOLVEnpm ERR! ERESOLVE could not resolvenpm ERR!npm ERR! While resolving: vue-admin-template4.4.0npm ERR! Found: webpack4.46.0npm ERR! node_modules/webpacknpm ERR! webpack"^4.0…...

HttpServletRequest和HttpServletResponse的获取与使用

相关笔记&#xff1a;【JavaWeb之Servlet】 文章目录 1、Servlet复习2、HttpServletRequest的使用3、HttpServletResponse的使用4、获取HttpServletRequest和HttpServletResponse 1、Servlet复习 Servlet是JavaWeb的三大组件之一&#xff1a; ServletFilter 过滤器Listener 监…...

css在线代码生成器

这里收集了许多有意思的css效果在线代码生成器适合每一位前端开发者 布局&#xff0c;效果类&#xff1a; 网格生成器https://cssgrid-generator.netlify.app/ CSS Grid Generator可帮助开发人员使用CSS Grid创建复杂的网格布局。网格布局是创建Web页面的灵活和响应式设计的强…...

在java中如何使用openOffice进行格式转换,word,excel,ppt,pdf互相转换

1.首先需要下载并安装openOffice,下载地址为&#xff1a; Apache OpenOffice download | SourceForge.net 2.安装后&#xff0c;可以测试下是否可用&#xff1b; 3.build.gradle中引入依赖&#xff1a; implementation group: com.artofsolving, name: jodconverter, version:…...

手机变电脑2023之虚拟电脑droidvm

手机这么大的内存&#xff0c;装个app来模拟linux&#xff0c;还是没问题的。 app 装好后&#xff0c;手指点几下确定按钮&#xff0c;等几分钟就能把linux桌面环境安装好。 不需要敲指令&#xff0c; 不需要对手机刷机&#xff0c; 不需要特殊权限&#xff0c; 不需要找驱…...

HDFS中的sequence file

sequence file序列化文件 介绍优缺点格式未压缩格式基于record压缩格式基于block压缩格式 介绍 sequence file是hadoop提供的一种二进制文件存储格式一条数据称之为record&#xff08;记录&#xff09;&#xff0c;底层直接以<key, value>键值对形式序列化到文件中 优…...

【MySQL】检索数据使用数据处理函数

函数 与其他大多数计算机语言一样&#xff0c;SQL支持利用函数来处理数据。函数一般是在数据上执行的&#xff0c;它给数据的转换和处理提供了方便。 函数没有SQL的可移植性强&#xff1a;能运行在多个系统上的代码称为可移植的。多数SQL语句是可移植的&#xff0c;而函数的可…...

【嵌入式学习笔记】嵌入式入门6——定时器TIMER

1.定时器概述 1.1.软件定时原理 使用纯软件&#xff08;CPU死等&#xff09;的方式实现定时&#xff08;延时&#xff09;功能有诸多缺点&#xff0c;如CPU死等、延时不精准。 void delay_us(uint32_t us) {us * 72;while(us--); }1.2.定时器定时原理 使用精准的时基&#…...

无法与IP建立连接,未能下载VSCode服务器

如题&#xff0c;在远程连接服务器的时候突然遇到了这个提示。 查阅了一圈&#xff0c;发现是VSCode版本自动更新惹的祸&#xff01;&#xff01;&#xff01; 在VSCode的帮助->关于这里发现前几天VSCode自动更新了&#xff0c;我的版本号变成了1.100.3 才导致了远程连接出…...

苍穹外卖--缓存菜品

1.问题说明 用户端小程序展示的菜品数据都是通过查询数据库获得&#xff0c;如果用户端访问量比较大&#xff0c;数据库访问压力随之增大 2.实现思路 通过Redis来缓存菜品数据&#xff0c;减少数据库查询操作。 缓存逻辑分析&#xff1a; ①每个分类下的菜品保持一份缓存数据…...

如何为服务器生成TLS证书

TLS&#xff08;Transport Layer Security&#xff09;证书是确保网络通信安全的重要手段&#xff0c;它通过加密技术保护传输的数据不被窃听和篡改。在服务器上配置TLS证书&#xff0c;可以使用户通过HTTPS协议安全地访问您的网站。本文将详细介绍如何在服务器上生成一个TLS证…...

相机Camera日志分析之三十一:高通Camx HAL十种流程基础分析关键字汇总(后续持续更新中)

【关注我,后续持续新增专题博文,谢谢!!!】 上一篇我们讲了:有对最普通的场景进行各个日志注释讲解,但相机场景太多,日志差异也巨大。后面将展示各种场景下的日志。 通过notepad++打开场景下的日志,通过下列分类关键字搜索,即可清晰的分析不同场景的相机运行流程差异…...

什么?连接服务器也能可视化显示界面?:基于X11 Forwarding + CentOS + MobaXterm实战指南

文章目录 什么是X11?环境准备实战步骤1️⃣ 服务器端配置(CentOS)2️⃣ 客户端配置(MobaXterm)3️⃣ 验证X11 Forwarding4️⃣ 运行自定义GUI程序(Python示例)5️⃣ 成功效果![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/55aefaea8a9f477e86d065227851fe3d.pn…...

关键领域软件测试的突围之路:如何破解安全与效率的平衡难题

在数字化浪潮席卷全球的今天&#xff0c;软件系统已成为国家关键领域的核心战斗力。不同于普通商业软件&#xff0c;这些承载着国家安全使命的软件系统面临着前所未有的质量挑战——如何在确保绝对安全的前提下&#xff0c;实现高效测试与快速迭代&#xff1f;这一命题正考验着…...

逻辑回归暴力训练预测金融欺诈

简述 「使用逻辑回归暴力预测金融欺诈&#xff0c;并不断增加特征维度持续测试」的做法&#xff0c;体现了一种逐步建模与迭代验证的实验思路&#xff0c;在金融欺诈检测中非常有价值&#xff0c;本文作为一篇回顾性记录了早年间公司给某行做反欺诈预测用到的技术和思路。百度…...

关于uniapp展示PDF的解决方案

在 UniApp 的 H5 环境中使用 pdf-vue3 组件可以实现完整的 PDF 预览功能。以下是详细实现步骤和注意事项&#xff1a; 一、安装依赖 安装 pdf-vue3 和 PDF.js 核心库&#xff1a; npm install pdf-vue3 pdfjs-dist二、基本使用示例 <template><view class"con…...

土建施工员考试:建筑施工技术重点知识有哪些?

《管理实务》是土建施工员考试中侧重实操应用与管理能力的科目&#xff0c;核心考查施工组织、质量安全、进度成本等现场管理要点。以下是结合考试大纲与高频考点整理的重点内容&#xff0c;附学习方向和应试技巧&#xff1a; 一、施工组织与进度管理 核心目标&#xff1a; 规…...

WEB3全栈开发——面试专业技能点P4数据库

一、mysql2 原生驱动及其连接机制 概念介绍 mysql2 是 Node.js 环境中广泛使用的 MySQL 客户端库&#xff0c;基于 mysql 库改进而来&#xff0c;具有更好的性能、Promise 支持、流式查询、二进制数据处理能力等。 主要特点&#xff1a; 支持 Promise / async-await&#xf…...