当前位置:网站首页>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

Catalog

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 scenario

Let'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 idea

When 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 reminders

modify 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 dependencies

stay 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 order

There 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 !


原网站

版权声明
本文为[1024 Q]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206271524060228.html