redis 如何使密钥过期? [英] How does redis expire keys?

查看:42
本文介绍了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.

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

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

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

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

这篇关于redis 如何使密钥过期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆