Redis源码剖析之数据过时(expire)

我以前统计过咱们线上某redis数据被访问的时间分布,大概90%的请求只会访问最新15分钟的数据,99%的请求访问最新1小时的数据,只有不到千分之一的请求会访问超过1天的数据。咱们以前这份数据存了两天(近500g内存数据),若是算上主备的话用掉了120多个Redis实例(一个实例8g内存),光把过时时间从2天改为1天就能省下60多个redis实例,并且对原业务也没有啥太大影响。html

固然Redis已经实现了数据过时的自动清理机制,我所要作的只是改下数据写入时的过时时间而已。假设Redis没有数据过时的机制,咱们要怎么办? 大概一想就知道很麻烦,仔细想的话还得考虑不少的细节。因此我以为过时数据在缓存系统中是不起眼但很是重要的功能,除了省事外,它也能帮咱们节省不少成本。接下来咱们看下Redis中是如何实现数据过时的。git

实时清理

众所周知,Redis核心流程是单线程执行的,它基本上是处理完一条请求再出处理另一条请求,处理请求的过程并不只仅是响应用户发起的请求,Redis也会作好多其余的工做,当前其中就包括数据的过时。github

Redis在读写某个key的时候,它就会调用expireIfNeeded()先判断这个key是否已通过期了,若是已过时,就会执行删除。redis

int expireIfNeeded(redisDb *db, robj *key) {
    if (!keyIsExpired(db,key)) return 0;

    /* 若是是在slave上下文中运行,直接返回1,由于slave的key过时是由master控制的,
     * master会给slave发送数据删除命令。 
     * 
     * 若是返回0表示数据不须要清理,返回1表示数据此次标记为过时 */
    if (server.masterhost != NULL) return 1;
    if (checkClientPauseTimeoutAndReturnIfPaused()) return 1;

    /* 删除key */
    server.stat_expiredkeys++;
    propagateExpire(db,key,server.lazyfree_lazy_expire);
    notifyKeyspaceEvent(NOTIFY_EXPIRED,
        "expired",key,db->id);
    int retval = server.lazyfree_lazy_expire ? dbAsyncDelete(db,key) :
                                               dbSyncDelete(db,key);
    if (retval) signalModifiedKey(NULL,db,key);
    return retval;
}

判断是否过时也很简单,Redis在dictEntry中存储了上次更新的时间戳,只须要判断当前时间戳和上次更新时间戳之间的gap是否超过设定的过时时间便可。缓存

咱们重点来关注下这行代码。多线程

int retval = server.lazyfree_lazy_expire ? dbAsyncDelete(db,key) :
                                               dbSyncDelete(db,key);

lazyfree_lazy_expire 是Redis的配置项之一,它的做用是是否开启惰性删除(默认不开启),很显然若是开启就会执行异步删除,接下来咱们详细说下Redis的惰性删除。less

惰性删除

何为惰性删除,从本质上讲惰性删除就是新开一个线程异步处理数据删除的任务。为何要有惰性删除?众所周知,Redis核心流程是单线程执行,若是某个一步执行特别耗时,会直接影响到Redis的性能,好比删除一个几个G的hash key,那这个实例不直接原地升天。。 针对这种状况,须要新开启一个线程去异步删除,防止阻塞出Redis的主线程,固然Redis实际实现的时候dbAsyncDelete()并不彻底是异步,咱们直接看代码。异步

#define LAZYFREE_THRESHOLD 64
int dbAsyncDelete(redisDb *db, robj *key) {
    /* 从db->expires中删除key,只是删除其指针而已,并无删除实际值 */
    if (dictSize(db->expires) > 0) dictDelete(db->expires,key->ptr);

    /* If the value is composed of a few allocations, to free in a lazy way
     * is actually just slower... So under a certain limit we just free
     * the object synchronously. */
    /*
    * 在字典中摘除这个key(没有真正删除,只是查不到而已),若是被摘除的dictEntry不为
    * 空就去执行下面的释放逻辑 
    */
    dictEntry *de = dictUnlink(db->dict,key->ptr);
    if (de) {
        robj *val = dictGetVal(de);
        /* Tells the module that the key has been unlinked from the database. */
        moduleNotifyKeyUnlink(key,val);

        /* lazy_free并非彻底异步的,而是先评估释放操做所需工做量,若是影响较小就直接在主线程中删除了 */
        size_t free_effort = lazyfreeGetFreeEffort(key,val);

        /* 若是释放这个对象须要作大量的工做,就把他放到异步线程里作
         * 但若是这个对象是共享对象(refcount > 1)就不能直接释放了,固然这不多发送,但有可能redis
         * 核心会调用incrRefCount来保护对象,而后调用dbDelete。这我只须要直接调用dictFreeUnlinkedEntry,
         * 等价于调用decrRefCount */
        if (free_effort > LAZYFREE_THRESHOLD && val->refcount == 1) {
            atomicIncr(lazyfree_objects,1);
            bioCreateLazyFreeJob(lazyfreeFreeObject,1, val);
            dictSetVal(db->dict,de,NULL);
        }
    }

    /* 释放键值对所占用的内存,若是是lazyFree,val已是null了,只须要释放key的内存便可 */
    if (de) {
        dictFreeUnlinkedEntry(db->dict,de);
        if (server.cluster_enabled) slotToKeyDel(key->ptr);
        return 1;
    } else {
        return 0;
    }
}
  1. 首先在db->expires中把这个key给删除掉,(db->expires保存了全部带有过时时间数据的key,方便作数据过时)
  2. 而后把这个数据节点从db中摘掉,数据实际还在内存里,只是查不到而已。
  3. 接下来就是要清理数据了,redis并非直接把清理工做放到异步线程里作,而是调用lazyfreeGetFreeEffort()来评估清理工做对性能的影响,若是影响较小,就直接在主线程里作了。反之影响太大才会将删除的任务提交到异步线程里。
  4. 释放key和val占用的内存空间,若是是异步删除,val已是null,这里只须要释放key占用的空间便可。

这里第三步中为何异步删除不彻底是异步? 我以为仍是得从异步任务提交bioCreateLazyFreeJob()中一窥端倪。ide

void bioCreateLazyFreeJob(lazy_free_fn free_fn, int arg_count, ...) {
    va_list valist;
    /* Allocate memory for the job structure and all required
     * arguments */
    struct bio_job *job = zmalloc(sizeof(*job) + sizeof(void *) * (arg_count));
    job->free_fn = free_fn;

    va_start(valist, arg_count);
    for (int i = 0; i < arg_count; i++) {
        job->free_args[i] = va_arg(valist, void *);
    }
    va_end(valist);
    bioSubmitJob(BIO_LAZY_FREE, job);
} 

void bioSubmitJob(int type, struct bio_job *job) {
    job->time = time(NULL);
    // 多线程须要加锁,把待处理的job添加到队列末尾
    pthread_mutex_lock(&bio_mutex[type]);
    listAddNodeTail(bio_jobs[type],job);
    bio_pending[type]++;
    pthread_cond_signal(&bio_newjob_cond[type]);
    pthread_mutex_unlock(&bio_mutex[type]);
}

我理解,在异步删除的时候须要加锁将异步任务提交到队列里,若是加锁和任务提交所带来的性能影响大于直接删除的影响,那么异步删除还不如同步呢。oop

按期抽样删除

这里思考下另一个问题,若是数据写入后就再也没有读写了,是否是实时清理的功能就没法触及到这些数据,而后这些数据就永远都会占用空间。针对这种状况,Redis也实现了按期删除的策略。众所周知,Redis核心流程是单线程执行,因此注定它不能长时间停下来去干某个特定的工做,因此Redis按期清理也是每次只作一点点。

/* 有两种清理模式,快速清理和慢速清理 */
void activeExpireCycle(int type) {
    /* Adjust the running parameters according to the configured expire
     * effort. The default effort is 1, and the maximum configurable effort
     * is 10. */
    unsigned long
    effort = server.active_expire_effort-1, /* Rescale from 0 to 9. */
    config_keys_per_loop = ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP +
                           ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP/4*effort,  // 每次抽样的数据量大小 
    config_cycle_fast_duration = ACTIVE_EXPIRE_CYCLE_FAST_DURATION +
                                 ACTIVE_EXPIRE_CYCLE_FAST_DURATION/4*effort, // 每次清理的持续时间
    config_cycle_slow_time_perc = ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC +
                                  2*effort,  // 最大CPU周期使用率 
    config_cycle_acceptable_stale = ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE-
                                    effort; // 可接受的过时数据占比 

    /* This function has some global state in order to continue the work
     * incrementally across calls. */
    static unsigned int current_db = 0; /* Last DB tested. */
    static int timelimit_exit = 0;      /* Time limit hit in previous call? */
    static long long last_fast_cycle = 0; /* When last fast cycle ran. */

    int j, iteration = 0;
    int dbs_per_call = CRON_DBS_PER_CALL;
    long long start = ustime(), timelimit, elapsed;

    /* When clients are paused the dataset should be static not just from the
     * POV of clients not being able to write, but also from the POV of
     * expires and evictions of keys not being performed. */
    if (checkClientPauseTimeoutAndReturnIfPaused()) return;
    // 快速清理 
    if (type == ACTIVE_EXPIRE_CYCLE_FAST) {
        /* Don't start a fast cycle if the previous cycle did not exit
         * for time limit, unless the percentage of estimated stale keys is
         * too high. Also never repeat a fast cycle for the same period
         * as the fast cycle total duration itself. */
        // 若是上次执行没有触发timelimit_exit, 跳过执行
        if (!timelimit_exit &&
            server.stat_expired_stale_perc < config_cycle_acceptable_stale)
            return;
        // 两个快速清理周期内不执行快速清理
        if (start < last_fast_cycle + (long long)config_cycle_fast_duration*2)
            return;

        last_fast_cycle = start;
    }

    /* We usually should test CRON_DBS_PER_CALL per iteration, with
     * two exceptions:
     *
     * 1) Don't test more DBs than we have.
     * 2) If last time we hit the time limit, we want to scan all DBs
     * in this iteration, as there is work to do in some DB and we don't want
     * expired keys to use memory for too much time. */
    if (dbs_per_call > server.dbnum || timelimit_exit)
        dbs_per_call = server.dbnum;

    /* We can use at max 'config_cycle_slow_time_perc' percentage of CPU
     * time per iteration. Since this function gets called with a frequency of
     * server.hz times per second, the following is the max amount of
     * microseconds we can spend in this function. 
     * config_cycle_slow_time_perc是清理所能占用的CPU周期数配置,这里将周期数转化为具体的时间 */
    timelimit = config_cycle_slow_time_perc*1000000/server.hz/100;
    timelimit_exit = 0;
    if (timelimit <= 0) timelimit = 1;

    if (type == ACTIVE_EXPIRE_CYCLE_FAST)
        timelimit = config_cycle_fast_duration; /* in microseconds. */

    /* Accumulate some global stats as we expire keys, to have some idea
     * about the number of keys that are already logically expired, but still
     * existing inside the database. */
    long total_sampled = 0;
    long total_expired = 0;
    
    for (j = 0; j < dbs_per_call && timelimit_exit == 0; j++) {
        /* Expired and checked in a single loop. */
        unsigned long expired, sampled;
        
        redisDb *db = server.db+(current_db % server.dbnum);

        /* Increment the DB now so we are sure if we run out of time
         * in the current DB we'll restart from the next. This allows to
         * distribute the time evenly across DBs. */
        current_db++;

        /* Continue to expire if at the end of the cycle there are still
         * a big percentage of keys to expire, compared to the number of keys
         * we scanned. The percentage, stored in config_cycle_acceptable_stale
         * is not fixed, but depends on the Redis configured "expire effort". */
        do {
            unsigned long num, slots;
            long long now, ttl_sum;
            int ttl_samples;
            iteration++;

            /* 若是没有可清理的,直接结束 */
            if ((num = dictSize(db->expires)) == 0) {
                db->avg_ttl = 0;
                break;
            }
            slots = dictSlots(db->expires);
            now = mstime();

            /* 若是slot的填充率小于1%,采样的成本过高,跳过执行,等待下次合适的机会。*/
            if (num && slots > DICT_HT_INITIAL_SIZE &&
                (num*100/slots < 1)) break;

            /* 记录本次采样的数据和其中过时的数量 */
            expired = 0;
            sampled = 0;
            ttl_sum = 0;
            ttl_samples = 0;
            // 每次最多抽样num个 
            if (num > config_keys_per_loop)
                num = config_keys_per_loop;

            /* 这里由于性能考量,咱们访问了hashcode的的底层实现,代码和dict.c有些类型,
             * 但十几年内很难改变。 
             * 
             * 注意:hashtable不少特定的地方是空的,因此咱们的终止条件须要考虑到已扫描的bucket
             * 数量。 但实际上扫描空bucket是很快的,由于都是在cpu 缓存行里线性扫描,因此能够多
             * 扫一些bucket */
            long max_buckets = num*20;
            long checked_buckets = 0;
            // 这里有采样数据和bucket数量的限制。 
            while (sampled < num && checked_buckets < max_buckets) {
                for (int table = 0; table < 2; table++) {
                    if (table == 1 && !dictIsRehashing(db->expires)) break;

                    unsigned long idx = db->expires_cursor;
                    idx &= db->expires->ht[table].sizemask;
                    dictEntry *de = db->expires->ht[table].table[idx];
                    long long ttl;

                    /* 遍历当前bucket中的全部entry*/
                    checked_buckets++;
                    while(de) {
                        /* Get the next entry now since this entry may get
                         * deleted. */
                        dictEntry *e = de;
                        de = de->next;

                        ttl = dictGetSignedIntegerVal(e)-now;
                        if (activeExpireCycleTryExpire(db,e,now)) expired++;
                        if (ttl > 0) {
                            /* We want the average TTL of keys yet
                             * not expired. */
                            ttl_sum += ttl;
                            ttl_samples++;
                        }
                        sampled++;
                    }
                }
                db->expires_cursor++;
            }
            total_expired += expired;
            total_sampled += sampled;

            /* 更新ttl统计信息 */
            if (ttl_samples) {
                long long avg_ttl = ttl_sum/ttl_samples;

                /* Do a simple running average with a few samples.
                 * We just use the current estimate with a weight of 2%
                 * and the previous estimate with a weight of 98%. */
                if (db->avg_ttl == 0) db->avg_ttl = avg_ttl;
                db->avg_ttl = (db->avg_ttl/50)*49 + (avg_ttl/50);
            }

            /* We can't block forever here even if there are many keys to
             * expire. So after a given amount of milliseconds return to the
             * caller waiting for the other active expire cycle. 
             * 不能一直阻塞在这里作清理工做,若是超时了要结束清理循环*/
            if ((iteration & 0xf) == 0) { /* check once every 16 iterations. */
                elapsed = ustime()-start;
                if (elapsed > timelimit) {
                    timelimit_exit = 1;
                    server.stat_expired_time_cap_reached_count++;
                    break;
                }
            }
            /*
             * 若是过时key数量超过采样数的10%+effort,说明过时测数量较多,要多清理下,因此
             * 继续循环作一次采样清理。     
             */
        } while (sampled == 0 ||
                 (expired*100/sampled) > config_cycle_acceptable_stale);
    }

    elapsed = ustime()-start;
    server.stat_expire_cycle_time_used += elapsed;
    latencyAddSampleIfNeeded("expire-cycle",elapsed/1000);

    /* Update our estimate of keys existing but yet to be expired.
     * Running average with this sample accounting for 5%. */
    double current_perc;
    if (total_sampled) {
        current_perc = (double)total_expired/total_sampled;
    } else
        current_perc = 0;
    server.stat_expired_stale_perc = (current_perc*0.05)+
                                     (server.stat_expired_stale_perc*0.95);
}

代码有些长,大体总结下其执行流程,细节见代码注释。

  1. 首先经过配置或者默认值计算出几个参数,这几个参数直接或间接决定了这些执行的终止条件,分别以下。
  • config_keys_per_loop: 每次循环抽样的数据量
  • config_cycle_fast_duration: 快速清理模式下每次清理的持续时间
  • config_cycle_slow_time_perc: 慢速清理模式下每次清理最大消耗CPU周期数(cpu最大使用率)
  • config_cycle_acceptable_stale: 可接受的过时数据量占比,若是本次采样中过时数量小于这个阈值就结束本次清理。
  1. 根据上述参数计算出终止条件的具体值(最大采样数量和超时限制)。
  2. 遍历清理全部的db。
  3. 针对每一个db在终止条件的限制下循环清理。

总结

Redis的数据过时策略比较简单,代码也不是特别多,但一如既然到处贯穿者性能的考虑。固然Redis只是提供了这样一个功能,若是想用好的话还得根据具体的业务需求和实际的数据调整过时时间的配置,就比如我在文章开头举的那个例子。

本文是Redis源码剖析系列博文,同时也有与之对应的Redis中文注释版,有想深刻学习Redis的同窗,欢迎star和关注。
Redis中文注解版仓库:https://github.com/xindoo/Redis
Redis源码剖析专栏:https://zxs.io/s/1h
若是以为本文对你有用,欢迎一键三连

本文来自https://blog.csdn.net/xindoo

相关文章
相关标签/搜索