redis 中的key值過時後,觸發通知事件web
一、建立springboot工程,建立監聽類redis
maven配置spring
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>1.5.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.5.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>1.5.10.RELEASE</version> <scope>test</scope> </dependency> </dependencies>
建立兩個類windows
RedisKeyExpirationListener
@Component public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener { public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) { super(listenerContainer); } /** * 針對redis數據失效事件,進行數據處理 * @param message * @param pattern */ @Override public void onMessage(Message message, byte[] pattern) { // 用戶作本身的業務處理便可,注意message.toString()能夠獲取失效的key String expiredKey = message.toString(); System.out.println(expiredKey); } }
RedisListenerConfig
@Configuration public class RedisListenerConfig { @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); return container; } }
二、redis配置springboot
使用默認配置,localhost:6379 不設置密碼 maven
而後在此基礎上把notify-keyspace-events Ex 這一行的註釋打開ide
啓動工程 redis-server.exe redis.windows.conf spring-boot
三、測試測試
執行命令 set a 1 ex 2spa
兩秒後觸發回調