本文内容为 http://www.redis.io/commands/expire 的翻译、注解、例子扩充及其它修改。感谢 Redis 作者 Antirez 为开源社区作出的贡献,本文保证最新、最准、最全以表示对其的敬意。欢迎留言纠错、提示更新或支持。
EXPIRE key seconds

对键 key 设置一个超时时间。在超时时间到期之后,该键会被自动删除。

Set a timeout on key. After the timeout has expired, the key will automatically be deleted. 

如果一个键关联了一个超时时间,在 Redis 术语中,它被称为不稳定的(Volatile)

A key with an associated timeout is often said to be volatile in Redis terminology.

超时时间只有在键被命令 DEL 删除或命令 SETGETSET 重写覆盖(Overwritten)时才会被清除。这意味着只是在概念上修改(Alter)键中的值,而不是用一个新值替换它的所有操作,都将让超时属性保持原封不动(Untouched)

the SET or GETSET commands. This means that all the operations that conceptually alter the value stored at the key without replacing it with a new one will leave the timeout untouched. For instance, incrementing the value of a key with INCR, pushing a new value into a list with LPUSH, or altering the field value of a hash with HSET are all operations that will leave the timeout untouched.

超时时间也可以被单独清除,使当前键重新变为永久键(Persistent key),使用命令 PERSIST 即可完成该操作。

The timeout can also be cleared, turning the key back into a persistent key, using the PERSIST command.

如果一个键被命令 RENAME 重命名,其关联的剩余存在时间将会被转移到新键名上。

The timeout can also be cleared, turning the key back into a persistent key, using the PERSIST command.

如果一个键被命令 RENAME 重写覆盖(Overwritten),比如键 Key_A 已经存在,然后又调用 RENAME Key_B Key_A 将其覆盖,在这种场景下,不论原始的 Key_A 是否关联了一个超时时间,新的键 Key_A 将会从键 Key_B 那继承所有的属性。

If a key is overwritten by RENAME, like in the case of an existing key Key_A that is overwritten by a call like RENAME Key_B Key_A, it does not matter if the original Key_A had a timeout associated or not, the new key Key_A will inherit all the characteristics of Key_B.
  • 如果超时设置成功,则返回 1

    如果键不存在,或超时未被设置,则返回 0

    1 if the timeout was set.

    0 if key does not exist or the timeout could not be set.

  • redis> SET mykey "Hello"
    OK
    redis> EXPIRE mykey 10
    (integer) 1
    redis> TTL mykey
    (integer) 10
    redis> SET mykey "Hello World"
    OK
    redis> TTL mykey
    (integer) -1
  • 可以对一个已经被设置超时属性的键调用命令 EXPIRE。在这种情况下,当前键的存在时间将被更新为一个新值。该特性带来了很多有用的应用,就比如下文中介绍导航会话设计模式的例子。

    It is possible to call EXPIRE using as argument a key that already has an existing expire set. In this case the time to live of a key is updated to the new value. There are many useful applications for this, an example is documented in the Navigation session pattern section below.
  • Redis2.1.3 之前的版本中,修改一个带有存在时间的键将会使得整个键被删除,该语义是因之前响应层(Replication layer) 在实现上的限制而不得不这样,当然,现在已不存在该限制。

    In Redis versions prior 2.1.3 altering a key with an expire set using a command altering its value had the effect of removing the key entirely. This semantics was needed because of limitations in the replication layer that are now fixed.
  • Imagine you have a web service and you are interested in the latest N pages recently visited by your users, such that each adjacent page view was not performed more than 60 seconds after the previous. Conceptually you may think at this set of page views as a Navigation session if your user, that may contain interesting information about what kind of products he or she is looking for currently, so that you can recommend related products.

    You can easily model this pattern in Redis using the following strategy: every time the user does a page view you call the following commands:

    MULTI
    RPUSH pagewviews.user:http://.....
    EXPIRE pagewviews.user:<userid> 60
    EXEC

    If the user will be idle more than 60 seconds, the key will be deleted and only subsequent page views that have less than 60 seconds of difference will be recorded.

    This pattern is easily modified to use counters using INCR instead of lists using RPUSH.

  • Keys with an expire

    Normally Redis keys are created without an associated time to live. The key will simply live forever, unless it is removed by the user in an explicit way, for instance using the DEL command.

    The EXPIRE family of commands is able to associate an expire to a given key, at the cost of some additional memory used by the key. When a key has an expire set, Redis will make sure to remove the key when the specified amount of time elapsed.

    The key time to live can be updated or entirely removed using the EXPIRE and PERSIST command (or other strictly related commands).

    Expire accuracy

    In Redis 2.4 the expire might not be pin-point accurate, and it could be between zero to one seconds out.

    Since Redis 2.6 the expire error is from 0 to 1 milliseconds.

    Expires and persistence

    Keys expiring information is stored as absolute Unix timestamps (in milliseconds in case of Redis version 2.6 or greater). This means that the time is flowing even when the Redis instance is not active.

    For expires to work well, the computer time must be taken stable. If you move an RDB file from two computers with a big desync in their clocks, funny things may happen (like all the keys loaded to be expired at loading time).

    Even running instances will always check the computer clock, so for instance if you set a key with a time to live of 1000 seconds, and then set your computer time 2000 seconds in the future, the key will be expired immediately, instead of lasting for 1000 seconds.

    How Redis expires keys

    Redis keys are expired in two ways: a passive way, and an active way.

    A key is actively expired simply when some client tries to access it, and the key is found to be timed out.

    Of course this is not enough as there are expired keys that will never be accessed again. This keys should be expired anyway, so periodically Redis test a few keys at random among keys with an expire set. All the keys that are already expired are deleted from the keyspace.

    Specifically this is what Redis does 10 times per second:

    Test 100 random keys from the set of keys with an associated expire.

    Delete all the keys found expired.

    If more than 25 keys were expired, start again from step 1.

    This is a trivial probabilistic algorithm, basically the assumption is that our sample is representative of the whole key space, and we continue to expire until the percentage of keys that are likely to be expired is under 25%

    This means that at any given moment the maximum amount of keys already expired that are using memory is at max equal to max amount of write operations per second divided by 4.

    How expires are handled in the replication link and AOF file

    In order to obtain a correct behavior without sacrificing consistency, when a key expires, a DEL operation is synthesized in both the AOF file and gains all the attached slaves. This way the expiration process is centralized in the master instance, and there is no chance of consistency errors.

    However while the slaves connected to a master will not expire keys independently (but will wait for the DEL coming from the master), they'll still take the full state of the expires existing in the dataset, so when a slave is elected to a master it will be able to expire the keys independently, fully acting as a master.

  • 版本支持

    1.0.0+

    时间复杂度(Time complexity)

    O(1)