Home > Database > Redis > body text

An article to talk about expiration operations and expiration strategies in Redis

青灯夜游
Release: 2022-02-24 10:12:56
forward
2532 people have browsed it

This article will take you to understand the expiration operation and expiration strategy in Redis, introduce the four methods of setting expiration time in Redis, expired keys in persistence, expired key execution process, etc. I hope it will be helpful to everyone. !

An article to talk about expiration operations and expiration strategies in Redis

If there is no concept of expiration in Redis, this means that all the keys we write will always be saved in # as long as they are not actively deleted. ##Redis, and Redis is a memory-based database, and the memory space is very limited. [Related recommendations: Redis video tutorial]

Expiration operation

Expiration setting

## There are four main ways to set expiration time in #Redis

:

    expire key seconds
  • : Set key to expire after n seconds.
  • pexpire key milliseconds
  • : Set key to expire in n milliseconds.
  • expireat key timestamp
  • : Set key to expire after a certain timestamp (accurate to seconds).
  • pexpireat key millisecondsTimestamp
  • : Set key to expire after a certain timestamp (accurate to milliseconds).
  • You can use the command
ttl key

(in seconds) or pttl key (in milliseconds) to view the key How long does it take to expire.

Redis

You can use the time command to query the timestamp of the current time (accurate to seconds). Several methods for directly operating expiration time in strings, as listed below:

    set key value ex seconds
  • : Set the key value pair and specify expiration at the same time Time (accurate to seconds).
  • set key value px milliseconds
  • : Set the key value pair and specify the expiration time (accurate to milliseconds).
  • setex key seconds valule
  • : Set the key-value pair and specify the expiration time (accurate to seconds).

Remove the expiration timeUse the command:

persist key

You can remove the expiration time of the key value . -1 means never expires.

Java implements expiration operationsUse

Jedis

to implement operations on Redis, code : <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">public class TTLTest { public static void main(String[] args) throws InterruptedException { // 创建 Redis 连接 Jedis jedis = new Jedis(&quot;xxx.xxx.xxx.xxx&quot;, 6379); // 设置 Redis 密码(如果没有密码,此行可省略) jedis.auth(&quot;xxx&quot;); // 存储键值对(默认情况下永不过期) jedis.set(&quot;k&quot;, &quot;v&quot;); // 查询 TTL(过期时间) Long ttl = jedis.ttl(&quot;k&quot;); // 打印过期日志 // 过期时间:-1 System.out.println(&quot;过期时间:&quot; + ttl); // 设置 100s 后过期 jedis.expire(&quot;k&quot;, 100); // 等待 1s 后执行 Thread.sleep(1000); // 打印过期日志 // 执行 expire 后的 TTL=99 System.out.println(&quot;执行 expire 后的 TTL=&quot; + jedis.ttl(&quot;k&quot;)); } }</pre><div class="contentsignin">Copy after login</div></div>

More expiration operation methods

, as listed below:

    pexpire(String key, long milliseconds)
  • : Set n milliseconds expires later.
  • expireAt(String key, long unixTime)
  • : Expires after setting a certain timestamp (accurate to seconds).
  • pexpireAt(String key, long millisecondsTimestamp)
  • : Expires after setting a certain timestamp (accurate to milliseconds).
  • persist(String key)
  • : Remove expiration time.
    public class TTLTest {
        public static void main(String[] args) throws InterruptedException {
            // 创建 Redis 连接
            Jedis jedis = new Jedis("xxx.xxx.xxx.xxx", 6379);
            // 设置 Redis 密码(如果没有密码,此行可省略)
            jedis.auth("xxx");
            // 存储键值对(默认情况下永不过期)
            jedis.set("k", "v");
            // 查询 TTL(过期时间)
            Long ttl = jedis.ttl("k");
            // 打印过期日志
            System.out.println("过期时间:" + ttl);
            // 设置 100s 后过期
            jedis.expire("k", 100);
            // 等待 1s 后执行
            Thread.sleep(1000);
            // 打印过期日志
            System.out.println("执行 expire 后的 TTL=" + jedis.ttl("k"));
            // 设置 n 毫秒后过期
            jedis.pexpire("k", 100000);
            // 设置某个时间戳后过期(精确到秒)
            jedis.expireAt("k", 1573468990);
            // 设置某个时间戳后过期(精确到毫秒)
            jedis.pexpireAt("k", 1573468990000L);
            // 移除过期时间
            jedis.persist("k");
        }
    }
    Copy after login

Expired keys in persistence

Expired keys in RDB

RDB

The file is divided into two stages, RDB The file generation stage and the loading stage.

1. RDB file generation

RDB

Loading is divided into the following two situations:

If## If #Redis
    is the
  • main server operating mode, when loading the RDB file, the program will check the keys saved in the file, and expired keys will not be loaded into in the database. Therefore, expired keys will not affect the main server that loads the RDB file; If Redis
  • is running in
  • slave server mode, in When loading a RDB file, the key will be loaded into the database regardless of whether it has expired. But when the master and slave servers perform data synchronization, the data of the slave server will be cleared. So generally speaking, expired keys will not affect the slave server loading the RDB file.
  • RDB
The source code for file loading can be found in the

rdbLoad() function of the rdb.c file. The source code is as shown:

/* Check if the key already expired. This function is used when loading
* an RDB file from disk, either at startup, or when an RDB was
* received from the master. In the latter case, the master is
* responsible for key expiry. If we would expire keys here, the
* snapshot taken by the master may not be reflected on the slave. 
*
* 如果服务器为主节点的话,
* 那么在键已经过期的时候,不再将它们关联到数据库中去
*/
if (server.masterhost == NULL && expiretime != -1 && expiretime < now) {
    decrRefCount(key);
    decrRefCount(val);
    // 跳过
    continue;
}
Copy after login
Expired keys in AOF

1. AOF file writing

When Redis

starts with

AOF When the mode is persisted, if an expired key in the database has not been deleted, then the AOF file will retain the expired key. When the expired key is deleted, Redis A DEL command will be appended to the AOF file to explicitly delete the key value. 2. AOF rewriting

When performing AOF

rewriting, the key-value pairs in

Redis will be Checking Expired keys will not be saved to the rewritten AOF file and therefore will not have any impact on the AOF rewrite.

Expired keys of master-slave library

Redis 运行在主从模式下时,从库不会进行过期扫描,从库对过期的处理是被动的。也就是即使从库中的 key 过期了,如果有客户端访问从库时,依然可以得到 key 对应的值,像未过期的键值对一样返回。

从库的过期键处理依靠主服务器控制,主库在 key 到期时,会在 AOF 文件里增加一条 del 指令,同步到所有的从库,从库通过执行这条 del 指令来删除过期的 key

过期策略

Redis 中我们可以给一些元素设置过期时间,那当它过期之后 Redis 是如何处理这些过期键呢?

过期键执行流程

Redis 之所以能知道那些键值过期,是因为在 Redis 中维护了一个字典,存储了所有设置了过期时间的键值,我们称之为过期字典

An article to talk about expiration operations and expiration strategies in Redis

过期键源码分析

过期键存储在 redisDb 结构中,源代码在 src/server.h 文件中(基于 Redis 5):

/* Redis database representation. There are multiple databases identified
 * by integers from 0 (the default database) up to the max configured
 * database. The database number is the &#39;id&#39; field in the structure. */
typedef struct redisDb {
    dict *dict;                 /* 数据库键空间,存放着所有的键值对 */
    dict *expires;              /* 键的过期时间 */
    dict *blocking_keys;        /* Keys with clients waiting for data (BLPOP)*/
    dict *ready_keys;           /* Blocked keys that received a PUSH */
    dict *watched_keys;         /* WATCHED keys for MULTI/EXEC CAS */
    int id;                     /* Database ID */
    long long avg_ttl;          /* Average TTL, just for stats */
    list *defrag_later;         /* List of key names to attempt to defrag one by one, gradually. */
} redisDb;
Copy after login

过期键数据结构如下图所示:

An article to talk about expiration operations and expiration strategies in Redis

过期策略

Redis 会删除已过期的键值,以此来减少 Redis 的空间占用,但因为 Redis 本身是单线的,如果因为删除操作而影响主业务的执行就得不偿失了,为此 Redis 需要制定多个(过期)删除策略来保证正常执行的性能。

定时删除

在设置键值过期时间时,创建一个定时事件,当过期时间到达时,由事件处理器自动执行键的删除操作

  • 优点:保证内存可以被尽快地释放。
  • 缺点:在 Redis 高负载的情况下或有大量过期键需要同时处理时,会造成 Redis 服务器卡顿,影响主业务执行。

惰性删除

不主动删除过期键,每次从数据库获取键值时判断是否过期,如果过期则删除键值,并返回 null

  • 优点:因为每次访问时,才会判断过期键,所以此策略只会使用很少的系统资源。
  • 缺点:系统占用空间删除不及时,导致空间利用率降低,造成了一定的空间浪费。

源码解析

惰性删除的源码位于 src/db.c 文件的 expireIfNeeded 方法中,源码如下:

int expireIfNeeded(redisDb *db, robj *key) {
    // 判断键是否过期
    if (!keyIsExpired(db,key)) return 0;
    if (server.masterhost != NULL) return 1;
    /* 删除过期键 */
    // 增加过期键个数
    server.stat_expiredkeys++;
    // 传播键过期的消息
    propagateExpire(db,key,server.lazyfree_lazy_expire);
    notifyKeyspaceEvent(NOTIFY_EXPIRED,
        "expired",key,db->id);
    // server.lazyfree_lazy_expire 为 1 表示异步删除(懒空间释放),反之同步删除
    return server.lazyfree_lazy_expire ? dbAsyncDelete(db,key) :
                                         dbSyncDelete(db,key);
}
// 判断键是否过期
int keyIsExpired(redisDb *db, robj *key) {
    mstime_t when = getExpire(db,key);
    if (when < 0) return 0; /* No expire for this key */
    /* Don&#39;t expire anything while loading. It will be done later. */
    if (server.loading) return 0;
    mstime_t now = server.lua_caller ? server.lua_time_start : mstime();
    return now > when;
}
// 获取键的过期时间
long long getExpire(redisDb *db, robj *key) {
    dictEntry *de;
    /* No expire? return ASAP */
    if (dictSize(db->expires) == 0 ||
       (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
    /* The entry was found in the expire dict, this means it should also
     * be present in the main dict (safety check). */
    serverAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL);
    return dictGetSignedIntegerVal(de);
}
Copy after login

所有对数据库的读写命令在执行之前,都会调用 expireIfNeeded 方法判断键值是否过期,过期则会从数据库中删除,反之则不做任何处理。

An article to talk about expiration operations and expiration strategies in Redis

定期删除

每隔一段时间检查一次数据库,随机删除一些过期键

Redis 默认每秒进行 10 次过期扫描,此配置可通过 Redis 的配置文件 redis.conf 进行配置,配置键为 hz 它的默认值是 hz 10

注意:Redis 每次扫描并不是遍历过期字典中的所有键,而是采用随机抽取判断并删除过期键的形式执行的。

定期删除流程

  • 从过期字典中随机取出 20 个键。

  • 删除这 20 个键中过期的键。

  • 如果过期 key 的比例超过 25%,重复步骤 1。

同时为了保证过期扫描不会出现循环过度,导致线程卡死现象,算法还增加了扫描时间的上限,默认不会超过 25ms。

An article to talk about expiration operations and expiration strategies in Redis

  • 优点:通过限制删除操作的时长和频率,来减少删除操作对 Redis 主业务的影响,同时也能删除一部分过期的数据减少了过期键对空间的无效占用。
  • 缺点:内存清理方面没有定时删除效果好,同时没有惰性删除使用的系统资源少。

源码解析

定期删除的核心源码在 src/expire.c 文件下的 activeExpireCycle 方法中,源码如下:

void activeExpireCycle(int type) {
    static unsigned int current_db = 0; /* 上次定期删除遍历到的数据库ID */
    static int timelimit_exit = 0;      /* Time limit hit in previous call? */
    static long long last_fast_cycle = 0; /* 上一次执行快速定期删除的时间点 */
    int j, iteration = 0;
    int dbs_per_call = CRON_DBS_PER_CALL; // 每次定期删除,遍历的数据库的数量
    long long start = ustime(), timelimit, elapsed;
    if (clientsArePaused()) return;
    if (type == ACTIVE_EXPIRE_CYCLE_FAST) {
        if (!timelimit_exit) return;
        // ACTIVE_EXPIRE_CYCLE_FAST_DURATION 是快速定期删除的执行时长
        if (start < last_fast_cycle + ACTIVE_EXPIRE_CYCLE_FAST_DURATION*2) return;
        last_fast_cycle = start;
    }
    if (dbs_per_call > server.dbnum || timelimit_exit)
        dbs_per_call = server.dbnum;
    // 慢速定期删除的执行时长
    timelimit = 1000000*ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC/server.hz/100;
    timelimit_exit = 0;
    if (timelimit <= 0) timelimit = 1;
    if (type == ACTIVE_EXPIRE_CYCLE_FAST)
        timelimit = ACTIVE_EXPIRE_CYCLE_FAST_DURATION; /* 删除操作的执行时长 */
    long total_sampled = 0;
    long total_expired = 0;
    for (j = 0; j < dbs_per_call && timelimit_exit == 0; j++) {
        int expired;
        redisDb *db = server.db+(current_db % server.dbnum);
        current_db++;
        do {
            // .......
            expired = 0;
            ttl_sum = 0;
            ttl_samples = 0;
            // 每个数据库中检查的键的数量
            if (num > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP)
                num = ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP;
            // 从数据库中随机选取 num 个键进行检查
            while (num--) {
                dictEntry *de;
                long long ttl;
                if ((de = dictGetRandomKey(db->expires)) == NULL) break;
                ttl = dictGetSignedInteger
                // 过期检查,并对过期键进行删除
                if (activeExpireCycleTryExpire(db,de,now)) expired++;
                if (ttl > 0) {
                    /* We want the average TTL of keys yet not expired. */
                    ttl_sum += ttl;
                    ttl_samples++;
                }
                total_sampled++;
            }
            total_expired += expired;
            if (ttl_samples) {
                long long avg_ttl = ttl_sum/ttl_samples;
                if (db->avg_ttl == 0) db->avg_ttl = avg_ttl;
                db->avg_ttl = (db->avg_ttl/50)*49 + (avg_ttl/50);
            }
            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;
                }
            }
            /* 每次检查只删除 ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP/4 个过期键 */
        } while (expired > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP/4);
    }
    // .......
}
Copy after login

activeExpireCycle 方法在规定的时间,分多次遍历各个数据库,从过期字典中随机检查一部分过期键的过期时间,删除其中的过期键。

这个函数有两种执行模式,一个是快速模式一个是慢速模式,体现是代码中的 timelimit 变量,这个变量是用来约束此函数的运行时间的。快速模式下 timelimit 的值是固定的,等于预定义常量 ACTIVE_EXPIRE_CYCLE_FAST_DURATION,慢速模式下,这个变量的值是通过 1000000 * ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC/server.hz/100 计算的。

Redis 使用的过期策略

Redis 使用的是惰性删除加定期删除的过期策略

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of An article to talk about expiration operations and expiration strategies in Redis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template