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裏的鍵被動刪除。