redis配置文件开启键过期
# The "notify-keyspace-events" takes as argument a string that is composed
# of zero or multiple characters. The empty string means that notifications
# are disabled.
#
# Example: to enable list and generic events, from the point of view of the
# event name, use:
#
# notify-keyspace-events Elg
#
# Example 2: to get the stream of the expired keys subscribing to channel
# name __keyevent@0__:expired use:
#
# notify-keyspace-events Ex
#
# By default all notifications are disabled because most users don't need
# this feature and the feature has some overhead. Note that if you don't
# specify at least one of K or E, no events will be delivered.
springboot中实现键后的处理逻辑
- 订阅逻辑
public class KeyExpiredEventMessageListener implements MessageListener {
private final RedisTemplate redisTemplate;
public KeyExpiredEventMessageListener(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public void onMessage(Message message, byte[] pattern) {
String expiredKey = message.toString();
// 处理键过期事件逻辑
System.out.println("Key expired: " + expiredKey);
String[] keys = expiredKey.split("\\:");
redisTemplate.opsForHash().delete(keys[0], keys[1]);
}
}
- 注册组件
@Bean
public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory,
KeyExpiredEventMessageListener keyExpiredEventMessageListener) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(keyExpiredEventMessageListener, new PatternTopic("__keyevent@*__:expired"));//__keyevent@0__:expired #0代表redis中的db索引
return container;
}
@Bean
public KeyExpiredEventMessageListener keyExpiredEventMessageListener(RedisTemplate redisTemplate) {
return new KeyExpiredEventMessageListener(redisTemplate);
}
- 测试demo
@Test
public void hashsetExpire4() throws InterruptedException {
redisTemplate.opsForHash().put("h_set4", "a", "1");
redisTemplate.opsForHash().put("h_set4", "b", "2");
redisTemplate.opsForValue().set("h_set4:b", "2");
redisTemplate.expire("h_set4:b", Duration.ofSeconds(10));// 多次设置时,以最后一次为准,这时有效期重设为1分
Thread.sleep(1000 * 60);
}
测试用例中,在10秒后,由于h_set4:b这个键过期了,所以触发了KeyExpiredEventMessageListener
事件,最后将对应的hashset里的键被动删除。