Home > Blockchain >  Redis key expiry event in spring?
Redis key expiry event in spring?

Time:09-30

I have a key which 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

CodePudding user response:

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):

  • Related