Redis过期时间消失的细节


 

一、背景

之前无意间和一个朋友讨论过redis的key过期的问题,当key设置了过期时间如果key被更新过期时间还是否有效?

 

二、参考资料

《Redis深度历险》 钱文品

Redis的所有数据结构都可以设置过期时间,时间到了,Redis会自动删除相应的对象需要注意的是,过期是以对象为单位的,比如一个hash结构的过期是整个hash对象的过期,而不是其中的某个子key的过期。

还有一个需要特别注意的地方,加果一个字符串已经设置了过期时间,然后你调用set方法修改了它,它的过期时间会消失。

 

动手实验

可以在线练习https://try.redis.io/

也可以本地安装redis或者用dock拉取redis镜像然后自己试验一下

发现设置超期时间后,再次set则之前的超期时间失效,开发中要注意这个细节。

 

Redis 更新(set) key值 会重置过期时间问题

今天在开发的过程中遇到了一个Redis的问题: 当你在redis中插入一个key值,并且设置了对应过期时间. 当过期时间还没到的时候重新 更新 key值会导致 过期时间被刷新, 针对这个问题: 我查看了下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, GETSET会将key对应存储的值替换成新的,命令也会清除掉超时时间;如果list结构中添加一个数据或者改变hset数据的一个字段是不会清除超时时间的;如果想要通过set去覆盖值那就必须重新设置expire。

 

所以: 重新set , getset 会重置过期时间, 希望各位遇到这类问题,做好准备.

出处:https://blog.csdn.net/w605283073/article/details/90552242

出处:https://blog.csdn.net/weixin_38399962/article/details/82697498


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM