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);
控制台输出:
需要注意的是:
过期监听消息中返回的是,过期的键的key值,是没有返回value的
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。