一、建立springboot工程,建立監聽類web
maven配置redis
<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>
建立兩個類spring
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配置windows
使用默認配置,localhost:6379 不設置密碼 springboot
而後在此基礎上把notify-keyspace-events Ex 這一行的註釋打開maven
啓動工程 redis-server.exe redis.windows.conf ide
三、測試spring-boot
執行命令 set a 1 ex 2測試
兩秒後觸發回調spa