当前位置:网站首页>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 !
边栏推荐
- 专用发票和普通发票的区别
- 洛谷入门1【顺序结构】题单题解
- #28对象方法扩展
- 我想买固收+产品,但是不了解它主要投资哪些方面,有人知道吗?
- Use of abortcontroller
- SQL injection principle
- Excuse me, is it cost-effective to insure sunshine Optimus Prime term life insurance No. 7? What are the advantages of this product?
- 2022-2-15 learning the imitated Niuke project - Section 5 shows comments
- What is the London Silver code
- 16 -- 删除无效的括号
猜你喜欢

E ModuleNotFoundError: No module named ‘psycopg2‘(已解决)

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

开源二三事|ShardingSphere 与 Database Mesh 之间不得不说的那些事
MySQL中符号@的作用

Knowledge map model

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

28 object method extension

QT notes (XXVIII) using qwebengineview to display web pages

PSS: vous n'êtes qu'à deux niveaux du NMS Free + Lifting point | 2021 Paper

All you want to know about large screen visualization is here
随机推荐
February 16, 2022 freetsdb compilation and operation
Admixture usage document Cookbook
Luogu_ P1002 [noip2002 popularization group] crossing the river_ dp
Teach you how to package and release the mofish Library
Cesium uses mediastreamrecorder or mediarecorder to record screen and download video, as well as turn on camera recording. [transfer]
PolarDB-X开源版有没有支持 mysql5.7 的版本?
ReentrantLock、ReentrantReadWriteLock、StampedLock
Why can't the start method be called repeatedly? But the run method can?
Can polardb-x be accessed through the client of related tools as long as the client supporting JDBC / ODBC protocol is afraid?
Beginner level Luogu 1 [sequence structure] problem list solution
Let's talk about the process of ES Indexing Documents
How is the London Silver point difference calculated
Numerical extension of 27es6
熊市慢慢,Bit.Store提供稳定Staking产品助你穿越牛熊
HTTP Caching Protocol practice
Beginner level Luogu 2 [branch structure] problem list solution
What is the open source compatibility of the current version of polardb-x? mysql8?
【170】PostgreSQL 10字段类型从字符串修改成整型,报错column cannot be cast automatically to type integer
What is the London Silver unit
避孕套巨头过去两年销量下降40% ,下降原因是什么?