当前位置: 首页 > 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.定时器定时原理 使用精准的时基&#…...

【WiFi帧结构】

文章目录 帧结构MAC头部管理帧 帧结构 Wi-Fi的帧分为三部分组成&#xff1a;MAC头部frame bodyFCS&#xff0c;其中MAC是固定格式的&#xff0c;frame body是可变长度。 MAC头部有frame control&#xff0c;duration&#xff0c;address1&#xff0c;address2&#xff0c;addre…...

电脑插入多块移动硬盘后经常出现卡顿和蓝屏

当电脑在插入多块移动硬盘后频繁出现卡顿和蓝屏问题时&#xff0c;可能涉及硬件资源冲突、驱动兼容性、供电不足或系统设置等多方面原因。以下是逐步排查和解决方案&#xff1a; 1. 检查电源供电问题 问题原因&#xff1a;多块移动硬盘同时运行可能导致USB接口供电不足&#x…...

质量体系的重要

质量体系是为确保产品、服务或过程质量满足规定要求&#xff0c;由相互关联的要素构成的有机整体。其核心内容可归纳为以下五个方面&#xff1a; &#x1f3db;️ 一、组织架构与职责 质量体系明确组织内各部门、岗位的职责与权限&#xff0c;形成层级清晰的管理网络&#xf…...

uniapp手机号一键登录保姆级教程(包含前端和后端)

目录 前置条件创建uniapp项目并关联uniClound云空间开启一键登录模块并开通一键登录服务编写云函数并上传部署获取手机号流程(第一种) 前端直接调用云函数获取手机号&#xff08;第三种&#xff09;后台调用云函数获取手机号 错误码常见问题 前置条件 手机安装有sim卡手机开启…...

三分算法与DeepSeek辅助证明是单峰函数

前置 单峰函数有唯一的最大值&#xff0c;最大值左侧的数值严格单调递增&#xff0c;最大值右侧的数值严格单调递减。 单谷函数有唯一的最小值&#xff0c;最小值左侧的数值严格单调递减&#xff0c;最小值右侧的数值严格单调递增。 三分的本质 三分和二分一样都是通过不断缩…...

苹果AI眼镜:从“工具”到“社交姿态”的范式革命——重新定义AI交互入口的未来机会

在2025年的AI硬件浪潮中,苹果AI眼镜(Apple Glasses)正在引发一场关于“人机交互形态”的深度思考。它并非简单地替代AirPods或Apple Watch,而是开辟了一个全新的、日常可接受的AI入口。其核心价值不在于功能的堆叠,而在于如何通过形态设计打破社交壁垒,成为用户“全天佩戴…...

通过 Ansible 在 Windows 2022 上安装 IIS Web 服务器

拓扑结构 这是一个用于通过 Ansible 部署 IIS Web 服务器的实验室拓扑。 前提条件&#xff1a; 在被管理的节点上安装WinRm 准备一张自签名的证书 开放防火墙入站tcp 5985 5986端口 准备自签名证书 PS C:\Users\azureuser> $cert New-SelfSignedCertificate -DnsName &…...

02.运算符

目录 什么是运算符 算术运算符 1.基本四则运算符 2.增量运算符 3.自增/自减运算符 关系运算符 逻辑运算符 &&&#xff1a;逻辑与 ||&#xff1a;逻辑或 &#xff01;&#xff1a;逻辑非 短路求值 位运算符 按位与&&#xff1a; 按位或 | 按位取反~ …...

Python 高级应用10:在python 大型项目中 FastAPI 和 Django 的相互配合

无论是python&#xff0c;或者java 的大型项目中&#xff0c;都会涉及到 自身平台微服务之间的相互调用&#xff0c;以及和第三发平台的 接口对接&#xff0c;那在python 中是怎么实现的呢&#xff1f; 在 Python Web 开发中&#xff0c;FastAPI 和 Django 是两个重要但定位不…...

大数据驱动企业决策智能化的路径与实践

&#x1f4dd;个人主页&#x1f339;&#xff1a;慌ZHANG-CSDN博客 &#x1f339;&#x1f339;期待您的关注 &#x1f339;&#x1f339; 一、引言&#xff1a;数据驱动的企业竞争力重构 在这个瞬息万变的商业时代&#xff0c;“快者胜”的竞争逻辑愈发明显。企业如何在复杂环…...