Detail the steps for Redis to enable keyspace notifications for timeout notifications

  • 2020-10-31 22:02:54
  • OfStack

Redis section Settings

Modify configuration file redis.conf (Windows for

Open the configuration file (depending on where you installed it) and go to the Event notification section. Turn on the notify-ES14en-ES15en Ex annotation or add the configuration, where E stands for Keyevent, this notification returns the name of key and x for timeout events. If the ES21en-ES22en-ES23en "" configuration is not commented out, it will not take effect. Save and restart redis, 1 to restart using the current configuration file, such as src/ redis-ES27en redis.conf

The SpringBoot section Settings

Add redis dependencies


Add the redis configuration to the global configuration file application =
spring.redis.listen-pattern = __keyevent@0__:expired

listen-pattern fills in the timeout period, meaning that springboot will listen for timeout key space notifications issued by redis.

Create listener

public class TopicMessageListener implements MessageListener {
 public void onMessage(Message message, byte[] bytes) {
 byte[] body = message.getBody();
 byte[] channel = message.getChannel();
 System.out.println(new String(body));
 System.out.println(new String(channel));

Where message is the notification returned by redis, body is the name of key that timed out, and channel is the timeout event

Create the listener configuration class

public class RedisListenerConfiguration {

 public RedisMessageListenerContainer getListenerContainer(RedisConnectionFactory connectionFactory){
 // Create a connection container 
 RedisMessageListenerContainer container = new RedisMessageListenerContainer();
 // In the redis The connection 
 // Writes the type that needs to be listened to, called timeout listening 
 Topic topic = new PatternTopic("__keyevent@0__:expired");
 container.addMessageListener(new TopicMessageListener(), topic);
 return container;

Later, when a key value expires, redis sends a notification to be received by TopicMessageListener above, in which the corresponding business method can be invoked for business processing.


Related articles: