SpringBoot监听Redis的Key过期事件

2018-11-21 12:24:27

SpringBoot监听Redis的Key过期事件

在一些业务场景中,我们希望在Redis的key过期时,得到通知。

Redis的配置

  • 修改conf文件
  • notify-keyspace-events "Ex"
  • 该配置表示监听key的过期事件,默认未开启
  • 该配置的其他信息(可以监听N多事件),可以参阅配置文件的注释,非常详细

自定义监听器

该监听器会在key过期时候触发

  1. import java.nio.charset.StandardCharsets;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.data.redis.connection.Message;
  5. import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
  6. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
  7. public class KeyExpiredListener extends KeyExpirationEventMessageListener {
  8. private static final Logger LOGGER = LoggerFactory.getLogger(KeyExpiredListener.class);
  9. public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
  10. super(listenerContainer);
  11. }
  12. @Override
  13. public void onMessage(Message message, byte[] pattern) {
  14. String channel = new String(message.getChannel(),StandardCharsets.UTF_8);
  15. //过期的key
  16. String key = new String(message.getBody(),StandardCharsets.UTF_8);
  17. LOGGER.info("redis key 过期:pattern={},channel={},key={}",new String(pattern),channel,key);
  18. }
  19. }

@Confiugration配置

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.data.redis.connection.RedisConnectionFactory;
  5. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
  6. import io.javaweb.redis.listener.KeyExpiredListener;
  7. @Configuration
  8. public class RedisConfiguration {
  9. @Autowired
  10. private RedisConnectionFactory redisConnectionFactory;
  11. @Bean
  12. public RedisMessageListenerContainer redisMessageListenerContainer() {
  13. RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
  14. redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
  15. return redisMessageListenerContainer;
  16. }
  17. @Bean
  18. public KeyExpiredListener keyExpiredListener() {
  19. return new KeyExpiredListener(this.redisMessageListenerContainer());
  20. }
  21. }

往Redis写入一个key,并且设置过期时间

过期事件被触发


0
1
0

添加评论

正在回复:
取消
0
0
1
0