Redis processes the business after the invalid time effective key to replace the scheduled task query


Redis sets the invalid key, which provides a convenient function. After adding redis monitoring, it can partially replace the scheduled task;

Take a simple example

If the order is not paid, it will be cancelled after 30 minutes, and the order status will be changed.

In general, regular tasks query orders that are not paid for more than 30 minutes, according to the time and status, query once every 5 minutes or 10 minutes, and then change the status.
Redis can monitor the key aging, and push messages after the key aging, so as to quickly process the cancellation order;

1、 Configure redis listener

public class RedisListenerConfig{

    RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory){

        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();


        return redisMessageListenerContainer;

2、 Key failure monitoring event push

Logical processing of redis invalid key
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener{

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {

     *For the redis data failure event, the data processing is carried out
     * @param message
     * @param pattern
    public void onMessage(Message message, byte[] pattern) {
        //Get invalid key
        String expiration = message.toString();
        //You can do logic processing here



After the redis key fails, only the key value can be obtained, and the value is not. Therefore, when setting the key, it is better to set the expiration time for the key storage with the unique ID of the order;

This is just a simple way of thinking, which also needs to consider data persistence and other issues;

It’s not easy to code. It’s all about acting