Redis专题三:key的过期
当timeout时间到期时,key会被redis自动删除,新建key默认是永远不会过期的
timeout相关命令
命令 | 解释 | 返回值 |
---|---|---|
EXPIRE key second |
为key设置timeout,单位为秒 | 1表示timeout设置成功 0表示key不存在 |
EXPIRE key milliseconds |
为key设置timeout,单位为毫秒 | 1表示timeout设置成功 0表示key不存在 |
TTL key |
key还有多少秒超时 | -2表示key不存在 -1表示key存在且没有过期 其它非负值表示过期的剩余秒数 |
PTTL key |
key还有多少毫秒超时 | -2表示key不存在 -1表示key存在且没有过期 其它非负值表示过期的剩余毫秒数 |
EXPIREAT key second_timestamp |
设置key在未来的一个时刻过期,值为从1970-1-1 到指定未来时间的时间间隔,单位为秒 |
1表示timeout设置成功 0表示key不存在 |
PEXPIREAT key milliseconds_timestamp |
设置key在未来的一个时刻过期,值为从1970-1-1 到指定未来时间的时间间隔,单位为毫秒 |
1表示timeout设置成功 0表示key不存在 |
PERSIST key |
移除timeout,设置key永远不过期 | 1表示timeout被移除 0表示key不存在或者没有明确的timout,如默认新建的key SET connections 10 |
EXISTS key |
判断key是否存在 | 1表示key存在 0表示key不存在 |
DEL [key_0, ..., key_n] |
删除key,如果key不存在,会被忽略 | 返回成功删除key的个数 |
RENAME key_source key_dest |
将key_source重命名为key_dest,重命名成功的话key_source会被删除 | 返回OK |
RENAMENX key_source key_dest |
将key_source重命名为key_dest | 1表示重命名成功 0表示key存在 |
timeout改变条件
- 删除、修改key(
SET
DEL
GETSET
等)都会导致timeout被清除> SET connections 10 OK > EXPIRE connections 30 (integer) 1 > TTL connections (integer) 26 > DEL connections (integer) 1 > TTL connections (integer) -2
- 对key的内容改变(
INCR
LPUSH
等)不会导致timeout被清除> SET connections 10 OK > EXPIRE connections 30 (integer) 1 > TTL connections (integer) 27 > INCR connections (integer) 11 > TTL connections (integer) 16
- 使用
PERSIST
设置永不过期,会导致timeout被清除> SET connections 10 OK > EXPIRE connections 30 (integer) 1 > TTL connections (integer) 28 > PERSIST connections (integer) 1 > TTL connections (integer) -1
- 使用
RENAME key_source key_dest
key_source的timeout会被继承到key_dest> SET connections 10 OK > EXPIRE connections 30 (integer) 1 > RENAME connections conn OK > TTL conn (integer) 13
- 使用
EXPIRE
设置timeout为负数时,会导致key立即被删除> SET connections 10 OK > EXPIRE connections -1 (integer) 1 > EXISTS connections (integer) 0