Scenes
Spring boot
Implementing monitoring Redis key
failure events can deal with certain scenarios, such as: processing order expiration and automatic cancellation, user membership expiration...
Enable Redis key expiration callback notification
Redis
By default, the key expiration monitoring function is not enabled, and it needs to be manually modified in the configuration file.
Linux
operating system- Modify the configuration file
redis
in the installation directoryredis.conf
, and then findnotify-keyspace-events Ex
this line of code, which is commented out by default, just uncomment it (that is, delete the # in front). - There is also a situation where there is no such line, in this case just add this line directly.
- Then reboot
redis
.
- Modify the configuration file
Windows
operating systemredis.windows.conf
Find and two files in the installation directoryredis.windows-service.conf
, then modify the fields in these two files respectivelynotify-keyspace-events Ex
, and uncomment them.- Then restart
redis
,Windows
the restart command isredis-server.exe --service-start
.
Java code implements monitoring callback
Add Redis key expiration monitoring configuration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
@Configuration
public class RedisListenerConfig {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
}
Create a listener class
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
@Component
public class KeyExpiredListener extends KeyExpirationEventMessageListener {
public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
/**
* 使用该方法监听,当Redis的key失效的时候执行该方法
* @param message message must not be {@literal null}.
* @param pattern pattern matching the channel (if specified) - can be {@literal null}.
*/
@Override
public void onMessage(Message message, byte[] pattern) {
// 过期的Key
String expiraKey = message.toString();
System.out.println("该Key已失效:"+expiraKey);
}
}
The specified setting
Redis
value and its expiration timekey
Redis Setex
The command key
sets . If key
already exists, SETEX
the command will replace the old value.