Redis life time, Redis key setting lifetime

Source: Internet
Author: User
Tags redis redis version volatile


Redis provides a lifetime for the key, and the lifetime is permanent when no life time is specified. Redis will automatically delete this key when the time expires. You can use the expire command, the time unit seconds, if a key is set to a limited lifetime, then the set key will be reset when the value is again set to permanent:
SET Session:captcha sd2a
EXPIRE Session:captcha 600

Cancels the lifetime, the key lifetime is set to permanent, is persist:
PERSIST Session:captcha

View the lifetime of a key with the TTL command,-1 means permanent or, and expiration is deleted.
TTL Session:captcha

The Redis Incr,lpush,hset,zrem and other commands do not change the life time.
To control time precisely to millimeters, you need to pexpire and use Pttl to view the rest of the time.
What if you want to give an expiration time rather than a few seconds to expire? You need expireat and pexpireat. The Expireat parameter is the timestamp (in seconds) at expiration, and the Pexpireat parameter is the timestamp (milliseconds) when the expiration time
SET Session:captcha sd2a
Expireat Session:captcha 1399902009
Pexpireat Session:captcha 1399902009000

Application Scenario One: Access frequency limit: We limit each user 1 minutes to browse only 10 pages. 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 ' over 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 because, after joining the INCR limit:user1:192.168.1.2, the client was shut down before executing expire limit:user1:192.168.1.2 60. Then the key and the value are persisted. And the ID can only be accessed 10 times a lifetime. That's too bad.


Application Scenario Two: implementing caching. The list of 10,000 users is very resource-intensive, so we put the data into a key after the first calculation and then set the lifetime for the key. After 1 hours, the lifetime expires, key is deleted, and the new ranking is computed again and a temporary key is saved. We use pseudocode to implement:
Battle Charts
$rank = Get Cache:rank:fight
If not $rank
$rank = Calculate rank ()
MULTI
SET Cache:rank:fight $rank
EXPIRE Cache:rank:fight 3600
Exec

Redis is a memory storage database, if the memory is full of cache, Redis will be based on the configuration file to delete a certain cache. The configuration item is the MaxMemory parameter in the Redis configuration file, in bytes. When this limit is exceeded, unwanted keys are removed according to the maxmemory-policy parameters of the profile. The Maxmemory-policy optional rules are as follows: Four
1, Volatile-lru: Use the LRU algorithm to delete a key (set the key to life time).
2, Allkey-lru: Use the LRU algorithm to delete a key.
3, Volatile-random: Immediately delete a key (set the key to the time of life).
4, Allkey-random: Immediately delete a key.
5, Volatile-ttl: Delete The survival time is about to expire a key. is to remove the N keys, and then delete the key in N keys that are about to expire, instead of traversing all the keys to remove the impending expiration. How many is n? The configuration file is matched.
6, Nevication: Do not delete, return error.


Redis sets the expiration time for key –expire command

EXPIRE Key seconds

Sets the lifetime for the given key, which is automatically deleted when the key expires (the lifetime is 0).

In Redis, a key with a life time is called a "volatile" (volatile).

The lifetime can be removed by removing the entire key by using the DEL command, or overridden by the SET and Getset commands (overwrite), which means that if a command modifies (alter) a value of a key with a lifetime, instead of replacing it with a new key value (rep Lace) Its words, then the living time will not be changed.

For example, executing a INCR command on a key, Lpush a command on a list, or executing a hset command on a hash table does not modify the lifetime of the key itself.

On the other hand, if a key is renamed using RENAME, then the renamed Key has the same lifetime as before it was renamed.

Another possibility for the RENAME command is to try renaming a key with a lifetime to another another_key with a lifetime, when the old Another_key (and its lifetime) is deleted, and then the old key is renamed Another_key, so The new Another_key has the same life time as the original key.

Using the PERSIST command, you can remove key lifetimes without deleting the key, making the key A "persistent" (persistent) key again.

Update Live Time

You can perform a EXPIRE command on a key that already has a live time, and the new specified lifetime replaces the old lifetime.

The accuracy of the expiration time

In the Redis 2.4 version, the expiration time is delayed within 1 seconds--that is, even if the key has expired, it may be accessed within a second of the expiration, and in the new Redis 2.6, the delay is reduced to 1 milliseconds.

Redis 2.1.3 Before the difference

In the previous version of Redis 2.1.3, modifying a key with a live time would cause the entire key to be deleted, a behavior that was limited by the replication (replication) layer at the time, and is now fixed.

Available versions:
>= 1.0.0
Complexity of Time:
O (1)
return value:
The setting successfully returns 1.
Returns 0 when the key does not exist or it cannot set a lifetime for the key (for example, if you try to update the lifetime of the key in Redis below the 2.1.3 version).
redis> SET cache_page "www.google.com"
Ok

redis> EXPIRE cache_page 30 # Set an expiration time of 30 seconds
(integer) 1

redis> TTL cache_page # View remaining lifetimes
(integer) 23

Redis> EXPIRE cache_page 30000 # Update Expiration time
(integer) 1

Redis> TTL Cache_page
(integer) 29996
1. In the Redis version of less than 2.1.3, only the key can be set once expire. redis2.1.3 and later versions, you can use the expire command for key multiple times to update key expire time.
2. Redis terminology, the key to set the expire time is called: volatile keys. The meaning is unstable key.

3. If the set or del command is used on key, the expire time is also removed. Especially the set command, which needs to be noted when writing a program.
4. Prior to the redis2.1.3 version, Redis deletes the key if it is associated with a write operation (Lpush,lset) and other actions that trigger the modification of value. Other words:

Redis.expire (key,expiration);

Redis.lpush (Key,field,value);

Redis.get (key)//return null

After the redis2.1.3 version there is no such constraint, can be arbitrarily modified.

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 on the expiration of the key used lazy expiration: when the key to determine whether the expiration of the key, if expired, then the expiration of processing. Second, the volatile keys are sampled every second, and if there is an expiration key, then all expired keys are processed

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.