springboot+redis過期事件監聽實現過程解析
1 修改 redis.conf配置文件:
K Keyspace events, published with keyspace@ prefix事件E Keyevent events, published with keyevent@ prefixg Generic commands (non-type specific) like DEL, EXPIRE, RENAME, …$ String commandsl List commandss Set commandsh Hash commandsz Sorted set commandsx 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的過期事件:
@Configurationpublic class RedisListenerConfig { @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); return container; }}
3.書寫一個監聽器
@Slf4j@Componentpublic 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的
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: