Expired key trigger event - Spring data Redis Expired key trigger event - Spring data Redis spring spring

Expired key trigger event - Spring data Redis


At first, need to enable keyspace notification for expire event in redis.By default keyspace events notifications are disabled because while not very sensible the feature uses some CPU power. Notifications are enabled using the notify-keyspace-events of redis.conf or via the CONFIG SET.

notify-keyspace-events "Ex"

When you are done with redis, you need to configure your message listener with a pattern topic "__keyevent@*__:expired". Here goes the code sample.

Listener Class:

@Componentpublic class ExpirationListener implements MessageListener {    private static final Logger logger = LoggerFactory.getLogger(ExpirationListener.class);    @Override    public void onMessage(Message message, byte[] bytes) {        String key = new String(message.getBody());        logger.debug("expired key: {}", key);    }}

Configuration:

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