Home Database Redis Redis survival time setting

Redis survival time setting

Mar 26, 2020 am 09:41 AM
redis

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

See all articles