Springboot项目配置Redis中key过期回调事件

大部分的时间,Redis中的key过期,是不用回调的,但是特殊情况下,需要监听。

添加配置信息

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }
}

添加key过期监听器

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

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

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        System.out.println("当前过期key: " + key);
        super.onMessage(message, pattern);
    }
}

运行后,设置一个带有效时间的key,当过期后,key值将被打印