SpringBoot监听redis过期key触发方法

1.更改redis.conf 配置

notify-keyspace-events Ex

2.springboot配置监听bean

@Configuration
public class RedisListenerConfig {

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

3.配置监听key

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {


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

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //  获取失效的key
        String expiredKey = message.toString();
        if (expiredKey.indexOf("abc") != -1) {
            
        }
        System.out.println(expiredKey);
    }
}

你可能感兴趣的:(java,springboot,redis)