Redis listens for key expiration events

Reprinted in: You’ll understand at a glance! Springboot and Spring integrate Redis to monitor KEY failure events_Dazhi's Blog-CSDN Blog

principle

The principle is very simple, using the subscription/publishing structure that comes with redis. When the key expires, a subscription information will be published to the topic of the same library __keyevent@0__:expired, and the content of the information is the expired key. then subscribe to it

Modify redis configuration

For the window version, open redis.windows-service.conf

Crtl+F in the redis root directory, search for notify, find line 892 and notify0keyspace-eventschange it toEx
Insert image description here

#  K     Keyspace events, published with __keyspace@<db>__ prefix.
#  E     Keyevent events, published with __keyevent@<db>__ prefix.
#  g     Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
#  $     String commands
#  l     List commands
#  s     Set commands
#  h     Hash commands
#  z     Sorted set commands
#  x     Expired events (events generated every time a key expires)
#  e     Evicted events (events generated when a key is evicted for maxmemory)
#  A     Alias for g$lshzxe, so that the "AKE" string means all the events.

translate

K:keyspace 事件,事件以 keyspace@ 为前缀进行发布
E:keyevent 事件,事件以 keyevent@ 为前缀进行发布
g:一般性的,非特定类型的命令,比如del,expire,rename等
$:字符串特定命令
l:列表特定命令
s:集合特定命令
h:哈希特定命令
z:有序集合特定命令
x:过期事件,当某个键过期并删除时会产生该事件
e:驱逐事件,当某个键因 maxmemore 策略而被删除时,产生该事件
A:g$lshzxe的别名,因此”AKE”意味着所有事件

The same applies to the Linux version, modify the redis.conf configuration file

A small reminder, important: the docker image redis does not have a configuration file by default. You need to mount it yourself. I have never used docker and I don’t know how to do it.

Say important things three times and restart Redis! Restart Redis! Restart Redis!

Spring boot project

Introduce dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Add configuration

# 端口
spring.redis.port=6379
# 主机地址
spring.redis.host=127.0.0.1
# 选择库
spring.redis.database=0

Add related classes

Simple configuration of redis

@Configuration
public class RedisConfiguration {
    
    

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private KeyExpiredListener keyExpiredListener;

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer() {
    
    
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        // 配置监听器监听的主题关联
        Topic topic = new ChannelTopic("__keyevent@0__:expired");
        redisMessageListenerContainer.addMessageListener(keyExpiredListener, topic);
        return redisMessageListenerContainer;
    }
}

Write a listener

@Component
public class KeyExpiredListener implements MessageListener {
    
    
    private static Logger logger = LoggerFactory.getLogger(TestRecall.class);

    //这里是回调函数失效的时候回调用这个函数
    @Override
    public void onMessage(Message message, byte[] pattern) {
    
    
        logger.info("key 失效回调事件触发");

        System.out.println(new String(message.getBody()));
        System.out.println(new String(message.getChannel()));
        System.out.println(new String(pattern));

    }
}

test

/**
 * 实现ApplicationRunner接口
 * 在springboot启动时会自动开启一个线程执行此run方法
 */
@Component
public class TestRecall implements ApplicationRunner {
    
    

    private static Logger logger = LoggerFactory.getLogger(TestRecall.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
    
    
        // 设置一个缓存,3秒后过期
        redisTemplate.opsForValue().set("key", "大誌", 3, TimeUnit.SECONDS);
        logger.info("设置缓存成功");
    }
}

Guess you like

Origin blog.csdn.net/qq_42700109/article/details/131275665