1、先修改 redis 的配置文件 redis.conf,(win的配置文件为:redis.windows.conf )
默认是开启:notify-keyspace-events "" ,改为 notify-keyspace-events Ex
2、项目 pom.xml 加入 maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
(消息监听器容器和监听方法,我放在同一个文件夹里面,感觉美观点 ?)
3、创建Redis消息监听器容器
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; /** * 创建Redis消息监听器容器 */ @Configuration public class RedisListenerConfig { @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); return container; }
4、监听方法
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 RedisKeyExpirationListener extends KeyExpirationEventMessageListener{ public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) { super(listenerContainer); } @Override public void onMessage(Message message, byte[] pattern) { // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key String expiredKey = message.toString(); System.out.println(expiredKey); }
5、测试
@Test public void testRedis(){ redisService.cacheValue("5", "OK", 5); redisService.cacheValue("30", "OK", 30); redisService.cacheValue("15", "OK", 15); redisService.cacheValue("60", "OK", 60); }