SpringBoot监听redis过期key

1.更改redis.conf 配置 notify-keyspace-events

默认的是    notify-keyspace-events "" 

更改未 默认的是    notify-keyspace-events Ex
image.png

2.配置监听beng

@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();
        //  指定key 的前缀=xxxxxx,处理对应业务逻辑,
        if (expiredKey.indexOf("saToken") != -1) {
            String[] orderOn = expiredKey.split(":");
            System.out.println("token"超时"  );
        }
        System.out.println(expiredKey);
    }
}

测试


image.png

你可能感兴趣的:(SpringBoot监听redis过期key)