spring data redis key失效监听

@Configuration
public class RedisListenerConfig {

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }
}
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

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

    @Override
    public void onMessage(Message message, byte[] channel) {
        // 获取过期的key
        String expiredKey = message.toString();
        // 判断是否是想要监听的过期key
        if (expiredKey.contains("hello")) {
            // 分布式环境只执行一次
            Boolean absent = stringRedisTemplate.opsForValue().setIfAbsent(expiredKey, "IfAbsent", 30, TimeUnit.SECONDS);
            if (absent) {
                log.info("key: {}", expiredKey);
            }
        }
    }
}

你可能感兴趣的:(Redis)