springboot+redis过期事件监听

时间:2020-03-24
本文章向大家介绍springboot+redis过期事件监听,主要包括springboot+redis过期事件监听使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1 修改 redis.conf配置文件:

K Keyspace events, published with keyspace@ prefix事件
E Keyevent events, published with keyevent@ prefix
g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, …
$ String commands
l List commands
s Set commands
h Hash commands
z Sorted set commands
x Expired events (events generated every time a key expires)
e Evicted events (events generated when a key is evicted for maxmemory)
A Alias for g$lshzxe, so that the “AKE” string means all the events.
redis.conf 的默认的配置是:notify-keyspace-events ""
我们需要改为:notify-keyspace-events Ex
即对应上面的键的过期事件。修改玩这个重启一下redis

2 客户端来监听redis的过期事件:

@Configuration
public class RedisListenerConfig {
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }
}

3.书写一个监听器

@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

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

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
       log.info("expiredKey========="+expiredKey);
    }

4.查询方法中随便加了两个表中的不同id,一个30s,一个27s。

  redisUtil.set("UserId"+user.get(0).getId(),user.get(0).getId(),30);
  redisUtil.set("UserInfoId"+userInfo.get(0).getId(),userInfo.get(0).getId(),27);

控制台输出:

原文地址:https://www.cnblogs.com/red-star/p/12557965.html