nosql - redis expire 疑问

浏览:32日期:2022-08-22

问题描述

使用 redis-cli 设置 mykey, 并且设置其过期时间为 40s, 然后, 我再重新设置 mykey, 这时 mykey 的值会被重置, 我不明白的是为啥 过期时间也同时重置了?如果我仅仅想重置值, 不更改过期时间有没办法?

源码:

SET mykey 'Hello'EXPIRE mykey 40EXISTS mykeySET mykey 'Hello'EXISTS mykeyEXISTS mykey

问题解答

回答1:

上官方网站看了一下expire的说明:这样解释的:

The timeout will only be cleared by commands that delete or overwrite the contents of the key, including DEL, SET, GETSET and all the *STORE 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.

如果用DEL, SET, GETSET会将key对应存储的值替换成新的,命令也会清除掉超时时间;如果list结构中添加一个数据或者改变hset数据的一个字段是不会清除超时时间的;如果想要通过set去覆盖值那就必须重新设置expire。

点击链接

回答2:

EXPIREAT和EXPIRE 更新value都会重置过期时间。

set之前通过ttl获取到key的过期时间set之后再把ttl的值给设成过期时间

192.168.1.9:6379> set key valueOK192.168.1.9:6379> expire key 100(integer) 1192.168.1.9:6379> ttl key(integer) 98192.168.1.9:6379> set key value1OK192.168.1.9:6379> expire key 98(integer) 1192.168.1.9:6379> ttl key(integer) 96192.168.1.9:6379>

但这样子会有误差,不知道其他人有没有更好的方法。

相关文章: