Redis - 如果更新key之后, 其过期时间会变吗

在开发中遇到一个问题,使用redis中的set【针对于string类型】更新一个含有过期时间的key时,会使这个key的过期时间变成永久有效:

复制代码
127.0.0.1:6379> set test hello
OK
127.0.0.1:6379> expire test 1000
(integer) 1
127.0.0.1:6379> set test world
OK
127.0.0.1:6379> ttl test
(integer) -1
复制代码

查阅redis官方文档是这样介绍的:

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【适用string类型】、GETSET【适用string类型】和所有 *STORE 命令。 这意味着从概念上改变键中存储的值而不用新值替换它的所有操作都将保持过期时间不变。 例如,使用 INCR 增加键的值、使用 LPUSH 将新值推送到列表中或使用 HSET 更改哈希的字段值都是不会影响过期时间的操作。

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

1)测试:【hset 设置hash,key不会清除过期时间】

2)测试 :【list 新增元素,key不会清除过期时间】

3)测试:【set 新增元素,key不会清除过期时间】

4)测试:【zset 新增元素,key不会清除过期时间】

总结:

  在开发过程中要格外注意:redis中如果更新一个含有过期时间的key时,要具体看该key的数据类型。如果是string,则会清除过期时间;如果是hash、list、set、zset,则不会清除过期时间。

posted @   李若盛开  阅读(595)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2022-05-13 Golang - Map底层实现
点击右上角即可分享
微信分享提示