redis 如何使密钥过期?

编程入门 行业动态 更新时间:2024-10-24 08:25:30
本文介绍了redis 如何使密钥过期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Redis 如何实现key的过期?从这里我了解到Redis存储了key过期的时间,但是具体是怎么实现的呢?

How does Redis implement the expiration of keys? From here I learnt that Redis stores the time at which the key will expire, but how exactly is this implemented?

推荐答案

简而言之——对于每个 redis 对象,都有一个过期时间.除非您将对象设置为过期,否则该时间为永不".

In short - for each redis object, there is an expiration time. Unless you set the object to expire, that time is "never".

现在,过期机制本身是半惰性的.延迟过期意味着在读取对象之前您实际上不会使它们过期.当读取一个对象时,我们检查它的过期时间戳,如果它是过去的,我们什么都不返回,并在我们访问它的时候删除该对象.但问题是,如果一个键从来没有被触动过,它只会无缘无故地占用内存.

Now, the expiration mechanism itself is semi-lazy. Lazy expiration means that you don't actually expire the objects until they are read. When reading an object, we check its expiration timestamp, and if it's in the past, we return nothing, and delete the object while we're at it. But the problem is that if a key is never touched, it just takes up memory for no reason.

所以Redis增加了第二层随机主动过期.它只是一直读取随机密钥,当一个过期的密钥被触摸时,它会基于惰性机制被删除.这不会影响过期行为,它只是添加了过期键的垃圾收集".

So Redis adds a second layer of random active expiration. It just reads random keys all the time, and when an expired key is touched it is deleted based on the lazy mechanism. This does not affect the expire behavior, it just adds "garbage collection" of expired keys.

当然实际的实现比这个复杂,但这是主要思想.

Of course the actual implementation is more complicated than this, but this is the main idea.

您可以在此处阅读更多相关信息:redis.io/commands/expire

You can read more about it here: redis.io/commands/expire

活动过期周期的源代码可以在这里找到:github/antirez/redis/blob/a92921da135e38eedd89138e15fe9fd1ffdd9b48/src/expire.c#L98

And the source code for the active expiration cycle can be found here: github/antirez/redis/blob/a92921da135e38eedd89138e15fe9fd1ffdd9b48/src/expire.c#L98

更多推荐

redis 如何使密钥过期?

本文发布于:2023-11-17 08:16:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609435.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密钥   redis

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!