Search code examples
javaspringspring-bootredisjedis

Redis key expiry event in spring?


I have a key that expires after 30 seconds.

redisTemplate.expire(sessionId , 30, TimeUnit.SECONDS);

This is my listener:

@Service
public class RedisController implements MessageListener {

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // Get every expired key from below the code.
        String key = new String(message.getBody());
        System.out.println("expired key is: " + key);
    }
}

I have also set CONFIG SET notify-keyspace-events KEA, but I am not receiving any callback.


Solution

  • Though your listener looks good, I guess you are missing the configuration of the listener (source).

    @Bean
    RedisMessageListenerContainer keyExpirationListenerContainer(RedisConnectionFactory connectionFactory, ExpirationListener expirationListener) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(expirationListener, new PatternTopic("__keyevent@*__:expired"));
        container.setErrorHandler(e -> logger.error("There was an error in Redis key expiration listener container", e));
        return container;
    }
    

    I think you might also be interested in (I found them while skimming the JavaDoc API):