SoFunction
Updated on 2025-04-06

SpringBoot listens for Redis key expiration events (expiration listening)

introduce

Redis key expiration events are a very useful feature in Redis that trigger event notifications when keys expire. This is very useful for scenarios such as cache failure, session management, timing tasks, etc.

Redis configuration

Redis does not enable key expiration event notification by default, you need to enable this feature through configuration. Key expiration event notification can be enabled by modifying the file or using the CONFIG SET command.

notify-keyspace-events Ex

rely

<!--        operateredis-->
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Configuration File

spring:
  redis:
    host: localhost
    port: 6379
    #password: Use native redis, and I don't set the redis password    database: 0
    lettuce:
      pool:
        # Maximum blocking waiting time, negative numbers indicate no limit        max-wait: -1
        # Maximum free connection in the connection pool        max-idle: 5
        # Minimum idle connection in the connection pool        min-idle: 0
        # The maximum number of connections in the connection pool, negative number means no limit

Write key

@RestController
@RequiredArgsConstructor
public class BasicController {
    private final StringRedisTemplate stringRedisTemplate;
    @GetMapping("/hello")
    public String hello() {
        // Set key-value pairs and specify the expiration time of 10 seconds        ().set("product:123", "dpc", (5));
        // Get the value        String str = ().get("name");
        ("Value: " + str);
        return str;
    }
}

Configure the listener

@Configuration
public class RedisListenerConfig {

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        (connectionFactory);
        return container;
    }

    @Bean
    public OrderKeyExpirationListener orderKeyExpirationListener(RedisMessageListenerContainer container) {
        // Configure the listener to only listen to the `order:*` key        OrderKeyExpirationListener listener = new OrderKeyExpirationListener(container);
        (listener, new ChannelTopic("__keyevent@0__:expired"));
        return listener;
    }

    @Bean
    public SessionKeyExpirationListener sessionKeyExpirationListener(RedisMessageListenerContainer container) {
        // Configure the listener to only listen to the `session:*` key        SessionKeyExpirationListener listener = new SessionKeyExpirationListener(container);
        (listener, new ChannelTopic("__keyevent@0__:expired"));
        return listener;
    }

    @Bean
    public ProductKeyExpirationListener productKeyExpirationListener(RedisMessageListenerContainer container) {
        // Configure the listener to only listen to the `product:*` key        ProductKeyExpirationListener listener = new ProductKeyExpirationListener(container);
        (listener, new ChannelTopic("__keyevent@0__:expired"));
        return listener;
    }


}

Press KEY to monitor

Listen to session key

@Slf4j
public class SessionKeyExpirationListener extends KeyExpirationEventMessageListener {

    public SessionKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = ();
        if (("session:")) {
            ("Session【" + key + "】Expired");
            // Logic for processing session timeout        }
    }
}

Listen to the product key

@Slf4j
public class ProductKeyExpirationListener extends KeyExpirationEventMessageListener {
    public ProductKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = ();
        if (("product:")) {
            ("product【" + key + "】Expired");
            // Process product-related timeout logic        }
    }
}

Listen to the order key

public class OrderKeyExpirationListener extends KeyExpirationEventMessageListener {

    public OrderKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = ();
        (123);
        if (("order:")) {
            // Timeout logic related to processing orders        }
    }
}

This is the end of this article about SpringBoot listening for Redis key expiration events (expired listening). For more related SpringBoot listening for Redis expired content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!