当前位置:网站首页>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 !
边栏推荐
- Cesium 使用MediaStreamRecorder 或者MediaRecorder录屏并下载视频,以及开启摄像头录像。【转】
- PolarDB-X现在版本的开源兼容什么?mysql8?
- 2022年最新《谷粒学院开发教程》:8 - 前台登录功能
- Design of electronic calculator system based on FPGA (with code)
- [MySQL] query valid data based on time
- Google tool splits by specified length
- [issue 17] golang's one-year experience in developing Meitu
- [issue 18] share a Netease go classic
- PSS:你距離NMS-free+提點只有兩個卷積層 | 2021論文
- Top ten Devops best practices worthy of attention in 2022
猜你喜欢

SQL parsing practice of Pisa proxy

How is the London Silver point difference calculated

洛谷入门2【分支结构】题单题解

ReentrantLock、ReentrantReadWriteLock、StampedLock

【kotlin】第二天

SIGKDD22|图“预训练、提示、微调”范式下的图神经网络泛化框架

一场分销裂变活动,不止是发发朋友圈这么简单!

2022-2-15 learning the imitated Niuke project - Section 5 shows comments

带你认识图数据库性能和场景测试利器LDBC SNB

CentOS8-postgresql初始化时报错:initdb: error: invalid locale settings; check LANG and LC_* environment
随机推荐
Lei Jun lost another great general, and liweixing, the founding employee of Xiaomi No. 12, left his post. He once had porridge to create Xiaomi; Intel's $5.4 billion acquisition of tower semiconductor
保留有效位数;保留小数点后n位;
目前PolarDB-X是不支持数据库自制服务DAS么?
洛谷_P1007 独木桥_思维
Pisa-Proxy 之 SQL 解析实践
About tensorflow using GPU acceleration
Go error collection | when a function uses a return value with a parameter name
Basic configuration and usage of Jupiter notebook
[issue 18] share a Netease go classic
固收+产品有什么特点?
Design of direct spread spectrum communication system based on FPGA (with main code)
Top ten Devops best practices worthy of attention in 2022
一场分销裂变活动,不止是发发朋友圈这么简单!
What is the London Silver unit
About fast exponentiation
sql注入原理
Introduction to TTCAN brick moving
Design of electronic calculator system based on FPGA (with code)
Design of vga/lcd display controller based on FPGA (with code)
设计原则和思想:设计原则