Springboot Redis 过期监听

初始化配置

 @Bean
    RedisMessageListenerContainer keyExpirationListenerContainer(RedisConnectionFactory connectionFactory) {

        RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory);
        // 若是监听所有DB,则注释 下面代码
        listenerContainer.addMessageListener(new RedisListener(), new PatternTopic("__keyevent@8__:expired"));

        return listenerContainer;
    }

监听指定db


public class RedisListener implements MessageListener {


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("onPMessage pattern " + pattern + " " + " " + message);

        String s = message.toString();
        System.out.println("=-=-" + s);


    }
}

RedisTemplate 指定DB写入

 LettuceConnectionFactory jedisConnectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
        jedisConnectionFactory.setDatabase(10);
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        jedisConnectionFactory.resetConnection();

Redis 序列化

@Configuration
public class RedisSerializeConfig {
  private static final Logger LOG = LoggerFactory.getLogger(RedisSerializeConfig.class);

  @Bean
  @ConditionalOnMissingBean
  public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
      LOG.info("Start to initialize Redis...");
      ObjectMapper objectMapper = new ObjectMapper();
      objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
      objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

      Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
      jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

      RedisTemplate redisTemplate = new RedisTemplate();
      redisTemplate.setConnectionFactory(redisConnectionFactory);
      redisTemplate.setKeySerializer(new StringRedisSerializer());
      redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
      // redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
      LettuceConnectionFactory jedisConnectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
      jedisConnectionFactory.setDatabase(10);
      redisTemplate.setConnectionFactory(jedisConnectionFactory);
      jedisConnectionFactory.resetConnection();

      return redisTemplate;
  }
 
 

监听Redis所有DB过期数据


@Component
public class RedisListener extends KeyExpirationEventMessageListener {


    public RedisListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    //key 过期时调用
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("onPMessage pattern " + pattern + " " + " " + message);


    }
}

你可能感兴趣的:(Springboot Redis 过期监听)