当前位置:网站首页>Use redis to automatically cancel orders within 30 minutes
Use redis to automatically cancel orders within 30 minutes
2022-06-27 15:45:00 【1024 Q】
Business scenario
Realize the idea
Turn on Redis key Overdue reminders
Introduce dependencies
Related configuration
redis Expired monitoring really good ?
Implement the method of closing the order
Business scenarioLet's take the order function as an example :
After an order is generated, if it is not paid for a period of time, the order will be closed automatically . The simplest idea is to set up timed task polling , But the creation time of each order is different , Timing task rules cannot be set , If the interval between the scheduled tasks is set too short , Too much will affect efficiency .
There's another idea , When the user enters the order interface , Judge the time and perform related operations . There may be many ways , Here is a kind of monitor Redis Key value is used to close the order automatically according to the expiration time .
Realize the ideaWhen generating an order , towards Redis Add one KV Key value pair ,K Is the order number , Guarantee the passage of K You can locate an order in the database ,V It can be any value .
hypothesis , When an order is generated, send it to Redis In the store K Is the order number ,V It is also the key value pair of order number , And set the expiration time to 30 minute , If the key value pair is in 30 Can send a notification to the program after minutes expired , Or execute a method , Then we can solve the problem of order closing .
Realization : By monitoring Redis Provide the expiration queue to achieve , After listening to the expired queue , If Redis One of them KV The key value pair is out of date , Then a message will be sent to the listener , The listener can get the K, Be careful , You can't get V Of , Because it's overdue , That's what's mentioned above , Why make sure you get through K To locate the order , and V Is any value . Get K after , adopt K Positioning orders , And judge its state , If it's unpaid , Update to close , Or cancel the status .
Turn on Redis key Overdue remindersmodify redis Related event configuration . find redis The configuration file redis.conf, see notify-keyspace-events Configuration item , without , add to notify-keyspace-events Ex, If it's worth it , Then add Ex, The relevant parameters are as follows :
K:keyspace event , Events to [email protected] Publish for prefixes
E:keyevent event , Events to [email protected] Publish for prefixes
g: General , Non specific types of commands , such as del,expire,rename etc.
$: String specific commands
l: List specific commands
s: Set specific commands
h: Hash specific commands
z: An ordered set of specific commands
x: Overdue Events , This event occurs when a key is expired and deleted
e: Expulsion incident , When a key factor maxmemore When the policy is deleted , The event occurred
A:g$lshzxe Another name for , therefore ”AKE” It means all the events
Introduce dependenciesstay pom.xml Add org.springframework.boot:spring-boot-starter-data-redis rely on
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency>
Related configuration Define configuration RedisListenerConfig Implement monitoring Redis key Expiration time
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.listener.RedisMessageListenerContainer;@Configurationpublic class RedisListenerConfig { @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); return container; }}
Define a listener RedisKeyExpirationListener, Realization KeyExpirationEventMessageListener Interface , View source discovery , This interface listens to all db Expired event [email protected]*:expired"
import org.springframework.data.redis.connection.Message;import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;import org.springframework.data.redis.listener.RedisMessageListenerContainer;import org.springframework.stereotype.Component;/** * To monitor all db Expired event [email protected]*__:expired" */@Componentpublic class RedisKeyExpirationListener extends KeyExpirationEventMessageListener { public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) { super(listenerContainer); } /** * in the light of redis Data failure events , Data processing * @param message * @param pattern */ @Override public void onMessage(Message message, byte[] pattern) { // Get the invalid key, Cancel the order String expiredKey = message.toString(); System.out.println(expiredKey); }}
redis Expired monitoring really good ?stay Redis The official Manual of keyspace-notifications: timing-of-expired-events It is clearly stated in :
Basically expired events are generated when the Redis server deletes the key and not when the time to live theoretically reaches the value of zero
redis The implementation of automatic expiration is : Scheduled task offline scan and delete some expired keys ; Lazy checking for expiration when accessing keys and deleting expired keys .redis There is no guarantee that it will be deleted and sent an expiration notice at the set expiration time . actually , It is also common that the expiration notification is several minutes later than the set expiration time .
In addition, the key space notification is sent and forgotten (fire and forget) Strategy , Delivery is not guaranteed like message queuing . When a client subscribes to events, it will lose all the events distributed to it during disconnection .
This is a more “LOW” Solutions for , Not recommended .
Implement the method of closing the orderThere are several general implementation methods :
Use rocketmq、rabbitmq、pulsar Wait for the delayed delivery function of the message queue
Use redisson Provided DelayedQueue
There are some schemes that are widely circulated but have fatal defects , Don't use it to implement deferred tasks
Use redis Expired monitoring for
Use rabbitmq The dead letter line
Use non persistent time wheels
This is about using Redis Order realization 30 That's all for the article about automatic cancellation in minutes , More about Redis Order 30 Please search the previous articles of SDN or continue to browse the related articles below. I hope you can support SDN more in the future !
边栏推荐
- 设计原则和思想:设计原则
- Expert: those who let you go to a good school with a low score are all Scams
- SQL parsing practice of Pisa proxy
- Beginner level Luogu 1 [sequence structure] problem list solution
- 28 object method extension
- 利用Redis实现订单30分钟自动取消
- 【170】PostgreSQL 10字段类型从字符串修改成整型,报错column cannot be cast automatically to type integer
- 创建数据库并使用
- 带你认识图数据库性能和场景测试利器LDBC SNB
- 数学建模经验分享:国赛美赛对比/选题参考/常用技巧
猜你喜欢
VS编译遇到的问题
开源二三事|ShardingSphere 与 Database Mesh 之间不得不说的那些事
What is the London Silver unit
Vulnerability recurrence ----- 34. Yapi remote command execution vulnerability
#28对象方法扩展
Weekly snapshot of substrate technology 20220411
守护雪山之王:这些AI研究者找到了技术的新「用武之地」
Beginner level Luogu 2 [branch structure] problem list solution
substrate 技术每周速览 20220411
SIGKDD22|图“预训练、提示、微调”范式下的图神经网络泛化框架
随机推荐
设计原则和思想:设计原则
2022年最新《谷粒学院开发教程》:8 - 前台登录功能
All you want to know about large screen visualization is here
请问阿里云实验中 k8s 对于3306端口转发,同时开启mysql客户端就会异常终止,是什么原因呢?
About sitemap XML problems
28 object method extension
Creation and use of static library (win10+vs2022
【170】PostgreSQL 10字段类型从字符串修改成整型,报错column cannot be cast automatically to type integer
利用Redis实现订单30分钟自动取消
LeetCode每日一练(无重复字符的最长子串)
volatile与JMM
What is the London Silver code
Can polardb-x be accessed through the client of related tools as long as the client supporting JDBC / ODBC protocol is afraid?
Volatile and JMM
Expert: those who let you go to a good school with a low score are all Scams
Google tool splits by specified length
CAS之比较并交换
Fundamentals of software engineering (I)
OpenSSF安全计划:SBOM将驱动软件供应链安全
Redis CacheClient