springboot redis监控失效key
1.引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.创建超时监听
package com.jeesite.modules.test.RedisManage; 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; /** * redis失效key监听 * * @author 郑文 * */ @Component public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener { public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) { super(listenerContainer); } /** * redis失效key事件处理 * @param message * @param pattern */ @Override public void onMessage(Message message, byte[] pattern) { // message.toString()可以获取失效的key String expiredKey = message.toString(); System.out.println("-------------------"); System.out.println("失效key:"+message.getBody()); } }
3.超时监听配置
package com.jeesite.modules.test.RedisManage; 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.PatternTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; @Configuration public class RedisListenerConfig { @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); //下面这种方式是灵活配置,针对每个库的失效key做处理 //container.addMessageListener(new RedisExpiredListener(), new PatternTopic("__keyevent@0__:expired")); return container; } }
4. controller里接口调用
@Autowired public RedisTemplate redisTemplate; @GetMapping("/set") public String set() { redisTemplate.opsForValue().set("name", "tom"+System.currentTimeMillis(), 10, TimeUnit.SECONDS); return redisTemplate.opsForValue().get("name").toString(); }
5.10秒后控制台打印超时key