Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the operation of key value expiration in Redis

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article will explain in detail how to implement key expiration operation in Redis. The content of the article is of high quality. Therefore, Xiaobian shares it with you as a reference. I hope you have a certain understanding of relevant knowledge after reading this article.

1. expiration settings

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

expire key seconds: Set the key to expire in n seconds;

pexpire key milliseconds: Set the key to expire in n milliseconds;

expire key timestamp: Set the key to expire after a certain timestamp (accurate to seconds);

pexpire key millisecondsTimestamp: Set the key to expire after a certain timestamp (accurate to milliseconds);

The following is a look at the specific implementation of these commands separately.

1) expire: N seconds later

127.0.0.1:6379> set key valueOK127.0.0.1:6379> expire key 100(integer) 1127.0.0.1:6379> ttl key(integer) 97

The full name of ttl is Time To Live, which means the key expires in n seconds. For example, the result 97 above indicates that the key expires after 97s.

2) pexpire: Expire in N milliseconds

127.0.0.1:6379> set key2 value2OK127.0.0.1:6379> pexpire key2 100000(integer) 1127.0.0.1:6379> pttl key2(integer) 94524

where pexpire key2 100000 means that the set key2 expires in 100000 milliseconds (100 seconds).

3) expiration: expiration timestamp accurate to seconds

127.0.0.1:6379> set key3 value3OK127.0.0.1:6379> expireat key3 1573472683(integer) 1127.0.0.1:6379> ttl key3(integer) 67

Expire key3 1573472683 indicates that key3 expires after timestamp 1573472683 (accurate to seconds). Using ttl query, key3 will expire after 67s.

Tip: In Redis, you can use the time command to query the timestamp of the current time (accurate to seconds). Examples are as follows:

127.0.0.1:6379> time

1) "1573472563"

2) "248426"

4) pexpiration: expiration timestamp accurate to milliseconds

127.0.0.1:6379> set key4 value4OK127.0.0.1:6379> pexpireat key4 1573472683000(integer) 1127.0.0.1:6379> pttl key4(integer) 3522

Where pexpire key4 1573472683000 means that key4 expires (accurate to milliseconds) after timestamp 1573472683000. Using ttl query, you can find that key4 will expire after 3522 ms.

5) Expiration operations in strings

There are several ways to directly manipulate expiration time in strings, as listed below:

set key value ex seconds: Set the key value pair and specify the expiration time (accurate to seconds);

set key value ex milliseconds: Set the key value pair and specify the expiration time (accurate to milliseconds);

setex key seconds value: Sets the key-value pair and specifies the expiration time (to the nearest second).

An implementation example is as follows:

① set key value ex seconds

127.0.0.1:6379> set k v ex 100OK127.0.0.1:6379> ttl k(integer) 97

② set key value ex milliseconds

127.0.0.1:6379> set k2 v2 px 100000OK127.0.0.1:6379> pttl k2(integer) 92483

③ setex key seconds valule

127.0.0.1:6379> setex k3 100 v3OK127.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, as shown in the following code:

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

You can see that the first time you query k3 with ttl, it expires after 97s. When you query k3 with persist, the result is-1, which means k3 never expires.

3. Java implements expiration operations

This article uses the Jedis framework to manipulate Redis expiration times, as shown in the following code:

public class TTLTest { public static void main(String[] args) throws InterruptedException { //Create Redis join Jedis jedis = new Jedis("xxx.xxx.xxx.xxx", 6379);//Set Redis password (This line can be omitted if there is no password) jedis.auth("xxx"); //Store key-value pairs (Never expires by default) jedis.set ("k", "v"); //query TTL (expiration time) Long ttl = jedis.ttl("k"); //print expiration log System.out.println ("Expiration time: " + ttl); //Expire jedis.expire("k", 100) after 100s; //Thread.sleep(1000) after 1s; //Print expiration log System.out.println("TTL after expire =" + jedis.ttl("k")); }}

The results of the procedure are:

Expiration time: -1

TTL after expire =99

It can be seen that it is very convenient to use Jedis to manipulate the expiration time of Redis. You can directly use jedis.ttl("k") to query the life time of the key value, and use jedis.expire("k",seconds) to set the expiration time (accurate to seconds).

Tip: Before using Jedis, first introduce Jedis into the program. If you are using Maven project, add the following reference directly to pom.xml file:

redis.clients jedis version

More expired methods are listed below:

pexpire(String key, long milliseconds): Set to expire in n milliseconds;

expireAt(String key, long unixTime): expires after setting a timestamp (accurate to seconds);

pexpireAt(String key, long millisecond Timestamp): expires after setting a timestamp (accurate to milliseconds);

persist(String key): Remove expiration time.

The complete example code is as follows:

public class TTLTest { public static void main(String[] args) throws InterruptedException { //Create Redis join Jedis jedis = new Jedis("xxx.xxx.xxx.xxx", 6379);//Set Redis password (This line can be omitted if there is no password) jedis.auth("xxx"); //Store key-value pairs (Never expires by default) jedis.set ("k", "v"); //query TTL (expiration time) Long ttl = jedis.ttl("k"); //print expiration log System.out.println ("Expiration time: " + ttl); //Set expiration after 100s jedis.expire ("k", 100); //wait 1s and execute Thread.sleep(1000); //print expiration log System.out.println ("TTL after expire =" + jedis.ttl("k")); //set jedis.pexpire after n milliseconds ("k", 100000); //Expire after setting a timestamp (accurate to seconds) jedis. expire ("k", 1573468990); //Expire after setting a timestamp (accurate to milliseconds) jedis. pexpire ("k", 1573468990000L); //Remove expiration time jedis.persist("k"); }}

4. Expired keys in persistence

Above we talked about some use cases of expired keys in Redis normal operation, next, we look at how Redis handles expired keys in the persistence process.

Redis persistent files have two formats: RDB (Redis Database) and AOF (Append Only File). Let's look at the rendering state of expiration keys in these two formats respectively.

1) Expiration key in RDB

RDB files are divided into two phases, the RDB file generation phase and the loading phase.

① RDB file generation

When persisting from memory state to RDB (file), the key is checked for expiration, and expired keys are not saved to the new RDB file, so expired keys in Redis have no effect on the generation of new RDB files.

② RDB file loading

RDB loading is divided into the following two cases:

If Redis is running in master mode, when loading an RDB file, the program checks the keys stored in the file, and expired keys are not loaded into the database. Therefore, the expiration key does not affect the host server where the RDB file is loaded;

If Redis runs in slave mode, when loading an RDB file, it is loaded into the database regardless of whether the key expires. However, when the master and slave servers synchronize data, the data of the slave server will be emptied. Therefore, in general, expiration keys do not affect the slave server that loads the RDB file.

The source code for loading RDB files can be found in the rdbLoad() function of the rdb.c file, as shown in the source code:

/* 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 the server is the master node, * then when the keys have expired, they are no longer associated with the database */if (server.masterhost == NULL && expiretime != -1 && expiretime < now) { decrRefCount(key); decrRefCount(val); //Skip continue;}

2) Expiration key in AOF

① AOF file writing

When Redis is persisted in AOF mode, if an expired key in the database has not been deleted, the AOF file retains the expired key, and when the expired key is deleted, Redis appends a DEL command to the AOF file to explicitly delete the key.

② AOF rewrite

When performing an AOF rewrite, key-value pairs in Redis are checked. Expired keys are not saved to the rewritten AOF file, so there is no impact on the AOF rewrite.

5. Expiration key of master-slave library

When Redis is running in master-slave mode, the slave library does not scan for expiration, and the slave library is passive in processing expiration. That is, even if the key in the slave library expires, if a client accesses the slave library, it can still get the corresponding value of the key, and return it like an unexpired key-value pair.

The slave library's expired key processing depends on the master server's control. 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 deletes the expired key by executing this del instruction.

6. summary

In this article, we know four ways to set expiration time in Redis: expire, pexpire, expire, pexpire, among which the more common is expire to set the key value to expire in n seconds.

You can set the expiration time at the same time you add the key value to the string, and you can remove the expiration time using the persist command. We also know that expired keys are not recorded during RDB writes and AOF overwrites.

Expired keys In master-slave mode, the slave library handles expired keys completely depending on the master library, which sends del commands to all slave libraries after deleting expired keys.

The knowledge points of this article are shown in the following figure:

About how to implement key expiration operation in Redis to share here, I hope the above content can have some help for everyone, you can learn more knowledge. If you think the article is good, you can share it so that more people can see it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report