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 set the Redis time to Live

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

Share

Shulou(Shulou.com)06/01 Report--

How should Redis lifetime be set? This article mainly introduces in detail how to set the survival time of Redis. The sample code in this article is very detailed and has a certain reference value. Interested friends can refer to it.

Redis pairs provide time to live, which is permanent when no time to live is specified. Redis automatically deletes this key when the time expires. You can use the EXPIRE command, the unit of time in seconds. If a key is set to a limited lifetime, it will be set to permanent again when SET key is reassigned:

SET session:captcha sd2aEXPIRE session:captcha 600

Cancel the lifetime and set the key lifetime to permanent, which is PERSIST:

PERSIST session:captcha

Check the lifetime of a key with the TTL command, where-1 indicates permanent or expired deletion.

TTL session:captcha

The survival time will not be changed during commands such as Redis's INCR,LPUSH,HSET,ZREM.

To control the time to millimeters, you need PEXPIRE, and use PTTL to see the rest of the time.

What if you want to give an expiration time instead of a few seconds? You need EXPIREAT and PEXPIREAT. The parameter of EXPIREAT is the timestamp of expiration (seconds), and the parameter of PEXPIREAT is the timestamp of expiration (milliseconds).

SET session:captcha sd2aEXPIREAT session:captcha 1399902009PEXPIREAT session:captcha 1399902009000

Application scenario 1: access frequency restriction: we limit each user to 10 pages per minute. The pseudo code is as follows:

$isExists = EXISTS limit:user1:192.168.1.2if ($isExists) {$num = INCR limit:user1:192.168.1.2if ($num > 10) {print 'exceeds the limit' exit}} else {MULTI INCR limit:user1:192.168.1.2 EXPIRE limit:user1:192.168.1.2 60 EXEC}

The reason we used the transaction was that the client was shut down after INCR limit:user1:192.168.1.2 was executed and before EXPIRE limit:user1:192.168.1.2 60 was executed. Then the key and value will be persisted. And the ID can only be visited 10 times in its lifetime. This is too bad.

Application scenario 2: implement caching. It takes a lot of resources to calculate the ranking of 10, 000 users, so we save the data into a key after the first calculation, and then set the survival time for this key. When the survival time expires after 1 hour, the key is deleted, the new ranking is calculated again and a temporary key is saved. We use pseudocode to implement:

/ / Battle ranking $rank = GET cache:rank:fightif not $rank $rank = calculated ranking () MULTI SET cache:rank:fight $rank EXPIRE cache:rank:fight 3600 EXEC

Redis is a database stored in memory. If memory is full of caches, Redis will delete certain caches according to the configuration file. The configuration item is the maxmemory parameter in Redis's configuration file, in bytes. After this limit is exceeded, unwanted keys are deleted based on the maxmemory-policy parameter of the configuration file. The optional rules for maxmemory-policy are as follows:

1. Volatile-lru: use the LRU algorithm to delete a key (the key that sets the time to live).

2. Allkey-lru: delete a key using the LRU algorithm.

3. Volatile-random: delete a key (the key that sets the time to live).

4. Allkey-random: delete a key immediately.

5. Volatile-ttl: delete a key whose lifetime is about to expire. Is to immediately take out N keys, and then delete N keys that are about to expire, instead of traversing all the keys to delete those that are about to expire. What is N? The profile is matched.

6. Nevication: if not deleted, an error will be returned.

Redis sets the expiration time of Key-EXPIRE command

EXPIRE key seconds

Set the time to live for a given key, which is automatically deleted when the key expires (time to live is 0).

In Redis, a key with a lifetime is called a "volatile".

Lifetime can be removed by using the DEL command to delete the entire key, or can be overridden (overwrite) by the SET and GETSET commands, which means that if a command simply alter the value of a key with lifetime instead of replacing it with a new key value, then the lifetime will not be changed.

For example, performing INCR commands on a key, LPUSH commands on a list, or HSET commands on a hash table do not change the lifetime of the key itself.

On the other hand, if you use RENAME to rename a key, the survival time of the renamed key is the same as before.

Another possibility of the RENAME command is to try to rename one key with lifetime to another another_key with lifetime, where the old another_key (and its lifetime) is deleted, and the old key is renamed another_key, so that the new another_key has the same lifetime as the original key.

Using the PERSIST command, you can remove key's lifetime and make key a "persistent" key again without deleting the key.

Update time to Live

You can EXPIRE a key that already has a time to live, and the new time to live replaces the old time to live.

Accuracy of expiration time

In Redis 2.4, the delay in expiration time is less than 1 second-that is, even if key has expired, it may still be accessed within a second after expiration, while in the new Redis 2.6 version, the delay is reduced to less than 1 millisecond.

Differences before Redis 2.1.3

In versions prior to Redis 2.1.3, modifying a key with lifetime caused the entire key to be deleted, which was limited by the replication layer at that time, which has now been fixed. Available versions:

> = 1.0.0

Time complexity:

O (1)

Return value:

1 is returned if the setting is successful.

Return 0 when key does not exist or cannot set the lifetime for key (such as when you try to update the lifetime of key in versions earlier than 2.1.3 of Redis).

Redis > SET cache_page "www.google.com" OKredis > EXPIRE cache_page 30 # set expiration time to 30 seconds (integer) 1redis > TTL cache_page # View remaining time to live (integer) 23redis > EXPIRE cache_page 30000 # update expiration time (integer) 1redis > TTL cache_page (integer) 29996

1. In redis versions less than 2.1.3, you can only set expire on key once. In redis2.1.3 and later versions, you can use the expire command on key multiple times to update the expire time of key.

2. In redis terminology, the key with expire time set up is called volatile keys. It means unstable key.

3. If you use the set or del command on key, expire time will also be removed. Especially the set command, which needs to be paid attention to when writing programs.

4. In previous versions of redis2.1.3, redis deleted the value if it was written to volatile keys (LPUSH,LSET) and other operations triggered to modify the key.

In other words:

Redis.expire (key,expiration); redis.lpush (key,field,value); redis.get (key) / / return null

Later versions of redis2.1.3 do not have this constraint and can be modified at will.

Redis.set (key,100); redis.expire (key,expiration); redis.incr (key) redis.get (key) / / redis2.2.2 return 101; redis

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