search
HomeDatabaseRedisRedis 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

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

PERSIST session:captcha

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

TTL session:captcha

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

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
}

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

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

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

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

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;

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
This article is reproduced at:oschina. If there is any infringement, please contact admin@php.cn delete
Redis: Improving Application Performance and ScalabilityRedis: Improving Application Performance and ScalabilityApr 17, 2025 am 12:16 AM

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis: Exploring Its Data Model and StructureRedis: Exploring Its Data Model and StructureApr 16, 2025 am 12:09 AM

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis: Classifying Its Database ApproachRedis: Classifying Its Database ApproachApr 15, 2025 am 12:06 AM

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Why Use Redis? Benefits and AdvantagesWhy Use Redis? Benefits and AdvantagesApr 14, 2025 am 12:07 AM

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Understanding NoSQL: Key Features of RedisUnderstanding NoSQL: Key Features of RedisApr 13, 2025 am 12:17 AM

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

Redis: Identifying Its Primary FunctionRedis: Identifying Its Primary FunctionApr 12, 2025 am 12:01 AM

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis: A Guide to Popular Data StructuresRedis: A Guide to Popular Data StructuresApr 11, 2025 am 12:04 AM

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.

How to implement redis counterHow to implement redis counterApr 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.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.