当前位置:网站首页>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 !
边栏推荐
- Derivation of Halcon camera calibration principle
- #28对象方法扩展
- 设计原则和思想:设计原则
- 数学建模经验分享:国赛美赛对比/选题参考/常用技巧
- Unity3d best practices: folder structure and source control
- What is the London Silver unit
- 洛谷_P1003 [NOIP2011 提高组] 铺地毯_暴力枚举
- Top ten Devops best practices worthy of attention in 2022
- 洛谷_P1007 独木桥_思维
- Interview question: rendering 100000 data solutions
猜你喜欢

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

Google Earth Engine(GEE)——Export. image. The difference and mixing of toasset/todrive, correctly export classification sample data to asset assets and references

HTTP Caching Protocol practice

Is flutter easy to learn? How to learn? The most complete introduction and actual combat of flutter in history. Take it away without thanks~

守护雪山之王:这些AI研究者找到了技术的新「用武之地」

Knowledge map model
![[digital signal processing] discrete time signal (analog signal, discrete time signal, digital signal | sampling leads to time discrete | quantization leads to amplitude discrete)](/img/80/28d53985d56d64ca721b26e846c667.jpg)
[digital signal processing] discrete time signal (analog signal, discrete time signal, digital signal | sampling leads to time discrete | quantization leads to amplitude discrete)

Centos8 PostgreSQL initialization error: initdb: error: invalid locale settings; check LANG and LC_* environment

PSS:你距离NMS-free+提点只有两个卷积层 | 2021论文

漏洞复现----34、yapi 远程命令执行漏洞
随机推荐
Design of direct spread spectrum communication system based on FPGA (with main code)
可变参数模板 Variadic Templates
漏洞复现----34、yapi 远程命令执行漏洞
Piblup test report 1- pedigree based animal model
Eolink launched a support program for small and medium-sized enterprises and start-ups to empower enterprises!
Interview question: rendering 100000 data solutions
Scrapy framework (I): basic use
Design of FIR digital filter
洛谷入门1【顺序结构】题单题解
Eolink 推出面向中小企业及初创企业支持计划,为企业赋能!
About tensorflow using GPU acceleration
E ModuleNotFoundError: No module named ‘psycopg2‘(已解决)
What are the characteristics of fixed income + products?
专家:让你低分上好校的都是诈骗
PolarDB-X现在版本的开源兼容什么?mysql8?
A distribution fission activity is more than just a circle of friends!
保留有效位数;保留小数点后n位;
Beginner level Luogu 2 [branch structure] problem list solution
Create a database and use
Indexeddb learning materials