实验环境
操作系统: ubuntu-16.04-x64
redis版本: 4.0.9
概述
在实际的开发中经常遇到一些有时效的数据,使用关系数据库一般需要一个额外的字段来记录到期时间。在Redis中对key提供了生存时间的支持,到期后Redis会自动删除它。
命令
1.设置生存时间
EXPIRE key seconds
PEXPIRE key milliseconds
EXPIREAT key timestamp
PEXPIREAT key milliseconds-timestamp
EXPIRE命令的过期时间单位为秒,返回1表示设置成功,返回0表示设置失败或者或者键不存在。
127.0.0.1:6379> SET key1 test
OK
127.0.0.1:6379> EXPIRE key1 10
(integer) 1
127.0.0.1:6379> SET key1 test
OK
127.0.0.1:6379> DEL key1
(integer) 1
127.0.0.1:6379> EXPIRE key1 10
(integer) 0
PEXPIRE与EXPIRE命令使用上是一样的,唯一的区别是它支持的过期时间单位是毫秒。
EXPIREAT使用Unix时间戳作为第二个参数表示键的生存时间截至时间。
127.0.0.1:6379> SET key1 test
OK
127.0.0.1:6379> EXPIREAT key1 1527232560
(integer) 1
127.0.0.1:6379> TTL key1
(integer) 18
PEXPIREAT与EXPIREAT的区别是前者的生存时间是毫秒。
2.查看生存时间
TTL key
PTTL key
TTL返回键剩余的生存时间,单位是秒。当键过期后返回-2,没有为键设置生存时间时则返回-1。
127.0.0.1:6379> SET key1 test
OK
127.0.0.1:6379> EXPIRE key1 10
(integer) 1
127.0.0.1:6379> TTL key1
(integer) 5
127.0.0.1:6379> TTL key1
(integer) 4
127.0.0.1:6379> TTL key1
(integer) -2
127.0.0.1:6379> set key1 test
OK
127.0.0.1:6379> TTL key1
(integer) -1
3.取消生存时间
PERSIST key
PERSIST用于取消键的过期时间。如果生存时间被成功清楚则返回1,否则返回0。(键不存在或者键本来就是永久的)
127.0.0.1:6379> SET key1 test
OK
127.0.0.1:6379> EXPIRE key1 10
(integer) 1
127.0.0.1:6379> PERSIST key1
(integer) 1
127.0.0.1:6379> PERSIST key2
(integer) 0 # key2 不存在