Search code examples
spring-data-redis

How to configure and use KeyExpirationEventMessageListener with Redis Repositories?


Our application needs to listen to Redis key expired events and process the data in the key. Using RedisMessageListenerContainer I can get the expiry events but those only contain the expired key and not the key value. Hence wanted to use KeyExpirationEventMessageListener along with Redis Repository.

But am not able to configure KeyExpirationEventMessageListener and wanted some guidance for the same.


Solution

  • All you need to do is register an ApplicationListener for eg. RedisKeyExpiredEvent.

    @EnableRedisRepositories(enableKeyspaceEvents = EnableKeyspaceEvents.ON_STARTUP)
    public class Config {
    
        @Bean
        ApplicationListener<RedisKeyExpiredEvent<Person>> eventListener() {
            return event -> {
                System.out.println(String.format("Received expire event for key=%s with value %s.",
                        new String(event.getSource()), event.getValue()));
            };
        }
    }
    

    You can find a full sample here.