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

Time:2020-11-18

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

@Configuration
public class RedisListenerConfig{

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory){

        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();

        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);

        return redisMessageListenerContainer;
    }
    
}

2、 Key failure monitoring event push

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


    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

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

    }
}

Summary:

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