Key value expiration in redis

1. Expiration setting

There are four ways to set the expiration time in redis:

Let's take a look at the specific implementation of these commands.

1) Expire: expires in N seconds

127.0.0.1:6379> set key value
OK
127.0.0.1:6379> expire key 100
(integer) 1
127.0.0.1:6379> ttl key
(integer) 97

The full name of the command TTL is time to live, which means that the key value expires in N seconds. For example, the above result 97 indicates that the key expires after 97s.

2) Pexpire: expires in n milliseconds

127.0.0.1:6379> set key2 value2
OK
127.0.0.1:6379> pexpire key2 100000
(integer) 1
127.0.0.1:6379> pttl key2
(integer) 94524

Pexpire key2 indicates that key2 expires after 100000 milliseconds (100 seconds).

3) Expire: the expiration timestamp is accurate to seconds

127.0.0.1:6379> set key3 value3
OK
127.0.0.1:6379> expireat key3 1573472683
(integer) 1
127.0.0.1:6379> ttl key3
(integer) 67

Among them, expire Key3 1573472683 means that Key3 expires after the timestamp 1573472683 (accurate to seconds). Using TTL query, you can find that Key3 will expire after 67s.

4) Pexpireat: expiration timestamp accurate to milliseconds

127.0.0.1:6379> set key4 value4
OK
127.0.0.1:6379> pexpireat key4 1573472683000
(integer) 1
127.0.0.1:6379> pttl key4
(integer) 3522

Pexpirat key4 1573472683000 means that key4 expires after the timestamp 1573472683000 (accurate to milliseconds). Using TTL query, it can be found that key4 will expire after 3522 Ms.

5) Expiration operation in string

There are several methods to directly operate the expiration time in the string, as shown in the following list:

Implementation examples are as follows:

① set key value ex seconds

127.0.0.1:6379> set k v ex 100
OK
127.0.0.1:6379> ttl k
(integer) 97

② set key value ex milliseconds

127.0.0.1:6379> set k2 v2 px 100000
OK
127.0.0.1:6379> pttl k2
(integer) 92483

③ setex key seconds valule

127.0.0.1:6379> setex k3 100 v3
OK
127.0.0.1:6379> ttl k3
(integer) 91

2. Remove expiration time

Use the command: persist key to remove the expiration time of the key value, as shown in the following code:

127.0.0.1:6379> ttl k3
(integer) 97
127.0.0.1:6379> persist k3
(integer) 1
127.0.0.1:6379> ttl k3
(integer) -1

It can be seen that the first time you use TTL to query K3 will expire after 97s. After using the persist command, you can find that the result of querying the survival time of K3 is - 1, which means K3 will never expire.

3. Java implements expiration operation

This article will use the jedis framework to implement the operation of redis expiration time, as shown in the following code:

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"));
    }
}

The execution result of the program is:

It can be seen that it is convenient to use jedis to operate the expiration time of redis. You can use jedis directly TTL ("K") queries the lifetime of key values, using jedis The expire ("K", seconds) method sets the expiration time (accurate to seconds).

<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>version</version>
</dependency>

For more expiration methods, see the following list:

The complete example code is as follows:

public class TTLTest {
    public static void main(String[] args) throws InterruptedException {
        // 创建 Redis 连接
        Jedis jedis = new Jedis("xxx.xxx.xxx.xxx",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");
    }
}

4. Expiration key in persistence

We talked about some use cases of expired keys in the normal operation of redis. Next, let's see how redis handles expired keys in the process of persistence. There are two formats for redis persistent files: RDB (redis database) and AOF (append only file). Let's look at the rendering status of expired keys in these two formats.

1) Expired keys in RDB

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

① RDB file generation

When the memory state is persisted to RDB (file), the expiration check will be performed on the key, and the expired key will not be saved to the new RDB file. Therefore, the expired key in redis will not have any impact on the generation of the new RDB file.

② RDB file loading

RDB loading is divided into the following two cases:

The source code loaded by RDB file can be found in RDB C file. The source code is as follows:

/* 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;
}

2) Expiration key in AOF

① Aof file write

When redis persists in AOF mode, if an expired key in the database has not been deleted, the AOF file will retain the expired key. When the expired key is deleted, redis will add a del command to the AOF file to explicitly delete the key value.

② Aof override

When performing AOF rewriting, key value pairs in redis will be checked. Expired keys will not be saved to the rewritten AOF file, so it will not have any impact on AOF rewriting.

5. Expiration key of master-slave Library

When redis is running in the master-slave mode, the slave database will not scan for expiration, and the slave database is passive in dealing with expiration. That is, if the key in the slave library is expired, if a client accesses the slave library, the corresponding value of the key can still be obtained and returned like an unexpired key value pair.

The processing of expired keys in the slave library depends on the master server. When the key expires, the master library will add a del instruction to the AOF file and synchronize it to all slave libraries. The slave library will delete the expired key by executing this del instruction.

6. Summary

In this article, we know four ways to set the expiration time in redis: expire, pexpire, expirat and pexpirat. The more common one is to set the expiration key value to expire after N seconds.

You can set the expiration time while adding the key value in the string, and you can use the persist command to remove the expiration time. At the same time, we also know that expired keys will not be recorded during RDB writing and AOF rewriting.

Expired key in the master-slave mode, the processing of expired keys by the slave library completely depends on the master library. After the master library deletes the expired key, it will send del command to all slave libraries.

The knowledge points of this paper are shown in the figure below:

7. Quotation & acknowledgment

https://segmentfault.com/a/1190000017776475 https://www.cnblogs.com/lukexwang/p/4710333.html

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>