Home > Database > Redis > body text

Redis survival time setting

Release: 2020-03-26 09:41:55
forward
3921 people have browsed it

Redis survival time setting

Redis provides a survival time for keys. When the survival time is not specified, the survival time is permanent. Redis will automatically delete this key after the time expires. You can use the EXPIRE command, and the time unit is seconds. If a key is set to have a limited survival time, it will be set to permanent again when the SET key is reassigned:

SET session:captcha sd2a
EXPIRE session:captcha 600
Copy after login

Cancel the survival time, and The key's lifetime is set to permanent, which is PERSIST:

PERSIST session:captcha
Copy after login

Use the TTL command to view the lifetime of a key. -1 means permanent or deleted upon expiration.

TTL session:captcha
Copy after login

The survival time will not be changed during Redis' INCR, LPUSH, HSET, ZREM and other commands.

(Recommended: redis video tutorial)

If you want to control the time accurately to the millimeter, you need PEXPIRE, and use PTTL to check the remaining time.

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

SET session:captcha sd2a
EXPIREAT session:captcha 1399902009
PEXPIREAT session:captcha 1399902009000
Copy after login

Application scenario 1: Access frequency limit: We limit each user to 1 minute Can browse 10 pages. The pseudo code is as follows:

$isExists = EXISTS limit:user1:192.168.1.2
if($isExists){
    $num = INCR limit:user1:192.168.1.2
    if($num > 10){
        print '超过限制'
        exit
    }
}else{
    MULTI
    INCR limit:user1:192.168.1.2
    EXPIRE limit:user1:192.168.1.2 60
    EXEC
}
Copy after login

The reason we use transactions is because after executing INCR limit:user1:192.168.1.2 and before executing EXPIRE limit:user1:192.168.1.2 60, the client is added closed. Then the key and value will be persisted. And this ID can only be accessed 10 times in a lifetime. That's too bad.

Application scenario two: Implement caching. Calculating the rankings of 10,000 users is very resource-intensive, so we save the data into a key after the first calculation, and then set the survival time for this key. After one hour, the survival time expires, the key is deleted, and a new ranking is calculated again and a temporary key is saved. We use pseudo code to implement:

//战斗排行榜
$rank = GET cache:rank:fight
if not $rank
    $rank = 计算排名()
    MULTI
    SET cache:rank:fight $rank
    EXPIRE cache:rank:fight 3600
    EXEC
Copy after login

Redis is a database stored in memory. If the memory is full of cache, Redis will delete certain caches based on the configuration file. The configuration item is the maxmemory parameter in the Redis configuration file, and the unit is bytes. After this limit is exceeded, unnecessary keys will be deleted according to the maxmemory-policy parameter in the configuration file. The optional rules of maxmemory-policy are the following four:

1. volatile-lru: Use the LRU algorithm to delete a key (a key with a survival time set).

2. allkey-lru: Use the LRU algorithm to delete a key.

3. Volatile-random: Delete a key immediately (key with lifetime set).

4. allkey-random: Delete a key immediately.

5. volatile-ttl: Delete a key whose lifetime is about to expire. It is to take out N keys at once, and then delete the keys that are about to expire among the N keys, instead of traversing all the keys to delete the keys that are about to expire. What is N? Configuration file.

6. Nevication: Do not delete, return error.

Redis sets the expiration time of the Key - EXPIRE command

EXPIRE key seconds
Copy after login

Set the survival time for the given key. When the key expires (the survival time is 0), it will be automatically deleted.

In Redis, keys with survival time are called "volatile" (volatile).

The lifetime can be removed by deleting the entire key using the DEL command, or overwritten by the SET and GETSET commands. This means that if a command only modifies (alter) a key with a lifetime If the value of key is replaced with a new key value, the lifetime will not be changed.

For example, executing the INCR command on a key, executing the LPUSH command on a list, or executing the HSET command on a hash table, these operations will not modify the survival time of the key itself.

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

Another possibility of the RENAME command is to try to rename a key with a lifetime to another_key with a lifetime. At this time, the old another_key (and its lifetime) will be deleted, and then The old key will be renamed another_key. Therefore, the survival time of the new another_key is the same as the original key.

Use the PERSIST command to remove the key's lifetime without deleting the key, allowing the key to become a "persistent" key again.

Update survival time

You can execute the EXPIRE command on a key that already has a survival time, and the newly specified survival time will replace the old survival time.

Accuracy of expiration time

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

Differences before Redis 2.1.3

In versions before Redis 2.1.3, modifying a key with a survival time will cause the entire key to be Deletion, this behavior was due to limitations of the replication layer at the time, and this limitation has now been fixed. Available versions:

>= 1.0.0

Time complexity:

O(1)

Return value:

设置成功返回 1 。

当 key 不存在或者不能为 key 设置生存时间时(比如在低于 2.1.3 版本的 Redis 中你尝试更新 key 的生存时间),返回 0 。

redis> SET cache_page "www.google.com"
OK

redis> EXPIRE cache_page 30  # 设置过期时间为 30 秒
(integer) 1

redis> TTL cache_page    # 查看剩余生存时间
(integer) 23

redis> EXPIRE cache_page 30000   # 更新过期时间
(integer) 1

redis> TTL cache_page
(integer) 29996
Copy after login

1、在小于2.1.3的redis版本里,只能对key设置一次expire。redis2.1.3和之后的版本里,可以多次对key使用expire命令,更新key的expire time。

2、redis术语里面,把设置了expire time的key 叫做:volatile keys。 意思就是不稳定的key。

3、如果对key使用set或del命令,那么也会移除expire time。尤其是set命令,这个在编写程序的时候需要注意一下。

4、redis2.1.3之前的老版本里,如果对volatile keys 做相关写入操作(LPUSH,LSET),和其他一些触发修改value的操作时,redis会删除 该key。

也就是说 :

redis.expire(key,expiration);

redis.lpush(key,field,value);

redis.get(key) //return null
Copy after login

redis2.1.3之后的版本里面没有这个约束,可以任意修改。

redis.set(key,100);
redis.expire(key,expiration);
redis.incr(key)
redis.get(key)
//redis2.2.2 return 101; redis<2.1.3 return 1;
Copy after login

5、redis对过期键采用了lazy expiration:在访问key的时候判定key是否过期,如果过期,则进行过期处理。其次,每秒对volatile keys 进行抽样测试,如果有过期键,那么对所有过期key进行处理。

更多redis知识请关注redis入门教程栏目。

The above is the detailed content of Redis survival time setting. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:oschina.net
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