Redis 键的生存周期

变量在设置之后是一直存在的,直到使用命令清除

而有时需要变量存活一定的时间,到期后redis自动清除掉,而不是手工清理,这种情况下可以使用expire命令

expire key 时间(单位:秒)//指定变量的生存周期为多少秒

TTL key //查看变量的剩余生存周期时间,如果变量未指定生存周期(永久存在)则返回-1,如果变量不存在则返回-2

PERSIST key//使变量的生存周期失败,变为永久存在的

PERSIST命令之外,使用SET或GETSET命令为键赋值也会同时清除键的生存时间

localhost:6379> del index //删除index变量
(integer) 0
localhost:6379> ttl index//不存在变量返回-2
(integer) -2
localhost:6379> set index 1//设置index变量
OK
localhost:6379> expire index 30//设置index 变量生命周期为30秒
(integer) 1
localhost:6379> ttl index//查看变量生命周期剩余时间
(integer) 27
localhost:6379> persist index//持久化变量,生命周期为永久
(integer) 1
localhost:6379> ttl index//查看index 生命周期为-1(永久)
(integer) -1
localhost:6379> expire index 30//设置index 变量生命周期为30秒
(integer) 1
localhost:6379> ttl index//30秒之后变量消失
(integer) -2
localhost:6379> exists index//变已经不存在了
(integer) 0

猜你喜欢

转载自java12345678.iteye.com/blog/2165030