Redis过期事件真的不能用吗?

曾经用Redis的过期监听事件做过一些事情,比如定时通知的发送等等。但是最近看到一些文章说,Redis的过期监听事件有延时,这是真的吗?我要验证一下,不能人云亦云。

首先,搭建好测试环境;

  1. 确保本地安装redis;
  2. 建立一个SpringBoot整合redis的项目;
    SpringBoot整合Redis,订阅、发布、过期事件Redis集群下的过期监听事件notify-keyspace-events

接着,写个定时任务,存储key并设置过期时间;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 添加过期事件的定时任务
 * @author 程就人生
 * @Date
 */
@Component
public class RedisJob {
  
  private static final Logger log = LoggerFactory.getLogger(RedisJob.class);
  
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    
    // 日期格式化,精确到时分秒
    public DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 30秒执行一次
     */
    @Scheduled(cron = "*/30 * * * * ?")
    public void initKeys() {
      // 获取当前本地时间
        LocalDateTime now = LocalDateTime.now();
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        LocalDateTime begin = now.withMinute(0).withSecond(0).withNano(0);
        for (int i = 1; i < 16; i++) {
          // 在当前时间加上i小时
            setExpireKey(begin.plusHours(i), 8, operations);
        }
    }

    /**
     * 过期key的设置
     * @param expireTime
     * @param step
     * @param operations
     */
    private void setExpireKey(LocalDateTime expireTime, int step, ValueOperations<String, Object> operations) {
        LocalDateTime localDateTime = LocalDateTime.now().withNano(0);
        String nowTime = dateTimeFormatter.format(localDateTime);
        String key = null;
        Duration duration = null;
        while (expireTime.getMinute() < 55) {
        // key:当前时间@过期时间
          key = nowTime + "@" + dateTimeFormatter.format(expireTime);
        duration = Duration.between(LocalDateTime.now(), expireTime);
      // log.info("key = {}", key);
          operations.set(key, "A", duration);
          expireTime = expireTime.plusSeconds(step);     
        }       
    }
}

接下来,监听过期事件,计算出key延时时长;


import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * 过期监听事件
 * @author 程就人生
 * @Date
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
  
  private static final Logger log = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    public DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @Override
    public void onMessage(Message message, byte[] pattern) {
      // 获取过期的key
        String keyName = new String(message.getBody());
        // 对过期的key进行分割,获取过期时间
        LocalDateTime parse = LocalDateTime.parse(keyName.split("@")[1], dateTimeFormatter);
        // 计算出过期时长,当前时间-过期时间
        long seconds = Duration.between(parse, LocalDateTime.now()).getSeconds();
        // 打印真正过期时间,展示过期之后时间
        redisTemplate.execute((RedisCallback<Object>) connection -> {
            log.info("过期key:" + keyName + " ,滞后时间" + seconds);
            return null;
        });
    }
}

最后,查看测试结果:
当redis数据库的过期数据达到30W+的时候,我们看一下控制台输出的过期延时:

测试一下才知道,这延时时间够长的,30W+的数据延时达到10分钟了。而且还发现以下规律:

  • 过期key数据量越大,滞后时间越长;

  • 当通过客户端命令 keys * 访问时,可以发现延时时间明显缩短;

这是为什么呢?

官网 https://redis.io/docs/manual/keyspace-notifications/ 是这么说的:

Redis用两种方式过期具有生存时间的key:

  • 当命令访问key时,会先判断一下key是否过期,如果过期返回nil;
  • 通过后台系统,以增量方式查找过期的key,以便能够收集从未访问过的key。

redis的过期删除策略,采用了惰性删除和定期删除。

什么是惰性删除,什么是定期删除呢,再来理解几个概念:

1.定时删除

  • 对每一个设置了过期的key,建立一个定时器,一旦到达过期时间就立即删除。

  • 优点:可以立即清除过期数据,对内存友好;

  • 缺点:占用了大量的CPU去处理过期的数据。

2.惰性删除

  • 当访问一个key,才判断key是否过期,过期则删除返回nil,否则正常返回;

  • 优点:最大限制节省CPU资源;

  • 缺点:对内存不友好,对过期的key延迟删除;数据量越大,延时越久。

3.定期删除

  • 每隔一段时间,扫码redis过期key字典,并清除部分过期的key。定时删除和惰性删除的折中方案,还可以通过调整定时扫描的时间间隔和每次扫描的时间耗时,在不同情况下使得CPU和内存资源达到最优的平衡效果。

最后总结

Redis对key的过期策略采用了惰性删除和定期删除,因此过期key达到一定数量的时候,出现延时也就很正常了。另外在redis重启的时候,会将所有过期key一次性清除,这样就有可能监控不到过期事件,这也是需要注意的。如果只是使用redis过期一些数据,不关联过期事件,也是没有问题的。如果要监听过期事件,那就另寻它路吧。参考文档:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,427评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,551评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,747评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,939评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,955评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,737评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,448评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,352评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,834评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,992评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,133评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,815评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,477评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,022评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,147评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,398评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,077评论 2 355