Search code examples
redisspring-dataspring-data-redis

Spring data redis - listen to expiration event


I would like to listen expiration events with KeyExpirationEventMessageListener but I can't find an example.

Someone know how to do it using Spring boot 1.4.3 & Spring Data Redis?

I am currently doing this

    JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
    this.jedis = pool.getResource();
    this.jedis.psubscribe(new JedisPubSub() {
        @Override
        public void onPMessage(String pattern, String channel, String message) {
            System.out.println("onPMessage pattern " + pattern + " " + channel + " " + message);
            List<Object> txResults = redisTemplate.execute(new SessionCallback<List<Object>>() {
                public List<Object> execute(RedisOperations operations) throws DataAccessException {
                    operations.multi();
                    operations.opsForValue().get("val:" + message);
                    operations.delete("val:" + message);
                    return operations.exec();
                }
            });
            System.out.println(txResults.get(0));
        }
    }, "__keyevent@0__:expired");

And I would like to use Spring instead of Jedis directly.

Regards


Solution

  • Don't use KeyExpirationEventMessageListener as it triggers RedisKeyExpiredEvent which then leads to a failure in RedisKeyValueAdapter.onApplicationEvent.

    Rather use RedisMessageListenerContainer:

    @Bean
    RedisMessageListenerContainer keyExpirationListenerContainer(RedisConnectionFactory connectionFactory) {
    
        RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory);
    
        listenerContainer.addMessageListener((message, pattern) -> {
    
            // event handling comes here
    
        }, new PatternTopic("__keyevent@*__:expired"));
    
        return listenerContainer;
    }
    

    RedisMessageListenerContainer runs all notifications on an own thread.