Springboot listens to Redis cache expiration (Key invalidation) events

1. Redis configuration modification

Events are distributed through the Redis subscription and publishing function (pub/sub), so you need to enable redis event monitoring and publishing.
Modify the redis.conf file (redis.windows.conf and redis.windows-service.conf on Windows)

notify-keyspace-events Ex

2. The redis configuration class enables redis expiration monitoring


    /**
     * 开启 redis过期监听
     * @param connectionFactory
     * @return
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
    
    
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }

3. Define the key expiration listener and inherit KeyExpirationEventMessageListener

@Slf4j
@Component
public class RedisListener extends KeyExpirationEventMessageListener {
    
    

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

    /**
     * 针对redis缓存数据失效事件,进行后续数据处理
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
    
    
        /** key ,会把key返回,而不会将value返回*/
        String expiredKey = message.toString();
        log.info("过期缓存key:" + expiredKey);
        try {
    
    
            //登陆信息过期 若expiredKey以login开始则打印log
            if (expiredKey.startsWith("login")){
    
    
                log.info("---------redis 过期缓存处理");
            }

        } catch (Exception e) {
    
    
            log.info("---------redis 过期缓存处理 异常---------");
            e.printStackTrace();
        }

    }

}

By enabling the key expiration event notification, when the key expires, an expiration event will be published; we define a listener for the key expiration event, and when the key expires, a callback notification can be received.
Note:
  1) Since the Redis key expiration and deletion is timing + inertia, when there are too many keys, the deletion will be delayed, and the callback notification will also be delayed.
  2) The callback notification is one-time, and there is no ack mechanism. If the processing fails after receiving the notification, you will no longer receive the notification.
  3) The callback notification can only get the key, not the value.

Usage scenario:
  1) Delay queue can be implemented.
    The message is used as the key, and the time to be delayed is set as the TTL of the key. When the key expires, the listener will receive a notification to achieve the effect of delay.

Guess you like

Origin blog.csdn.net/god_sword_/article/details/131508245