springboot+redis 监听key过期事件,详细配置附代码!

修改 redis.conf配置文件

默认为notify-keyspace-events "", 修改为notify-keyspace-events Ex

springboot+redis 监听key过期事件,详细配置附代码!_第1张图片

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

maven依赖

  
        
            org.springframework.boot
            spring-boot-starter-data-redis
        

 配置文件中添加

 
import org.springframework.cache.annotation.EnableCaching;
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;
 
/**
 * @Author: szw
 * @Date: 2020/8/18 17:22
 */
@Configuration
@EnableCaching
public class RedisConfig {
    .....
 
    /**
     * 监听redis的过期事件
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }
}

创建监听

 
import lombok.extern.slf4j.Slf4j;
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;
 
/**
 * @Author: szw
 * @Date: 2020/8/20 15:54
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
 
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
 
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString(); // 获取过期的key
        if (expiredKey.contains("TIME_KEY")) { // 判断是否是想要监听的过期key
            log.info("redis key过期:{}", expiredKey);
            // TODO 业务逻辑
        }
    }
 
}

你可能感兴趣的:(spring,boot,redis,java)