当前位置:网站首页>Redis redis 】 【 the expiration of listening

Redis redis 】 【 the expiration of listening

2022-08-09 08:15:00 Ctrl Trainee - Brother Xie blog

redisExpired monitoring

使用场景:在我们项目中,Need to put payment for overtime orders,Operations such as updating status and rolling back inventory.在这里,使用redisExpired monitoring can do it

↓↓↓下面上代码↓↓↓

首先需要redisFor the monitoring to take effect, the following code needs to be configured

yml文件

在这里插入图片描述

RedisListenerConfig.java

@Slf4j
@Configuration
public class RedisListenerConfig {
    

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory) {
    
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        log.info("redisThe monitoring configuration takes effect");
        return container;
    }
}

使用
RedisKeyExpirationListener.java

@Slf4j
@Configuration
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    

    @Value("${spring.redis.database}")
    private Integer redisDatabase;

    private final RedisTemplate<String, String> redisTemplate;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer, RedisTemplate<String, String> redisTemplate) {
    
        super(listenerContainer);
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
    
        log.info("The expired listener event starts");
        RedisSerializer<?> serializer = redisTemplate.getValueSerializer();
        String channel = String.valueOf(serializer.deserialize(message.getChannel()));
        // 获取过期的Key值
        String body = String.valueOf(serializer.deserialize(message.getBody()));
        // DB0 key过期监听
        if (StrUtil.format("[email protected]{}__:expired", redisDatabase).equals(channel)) {
    
            System.out.println("第" + redisDatabase + "个DB库的key过期,key:" + body);
        }
    }
}

我们测试一下

在这里插入图片描述
等待30秒…

结果如下

在这里插入图片描述

总结

如果觉得不错,可以点赞+收藏或者关注下博主.感谢阅读!

原网站

版权声明
本文为[Ctrl Trainee - Brother Xie blog]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090800137921.html