Redis 过期,按规范内存泄漏?

Redis expiration, memory leak by specification?

Redis provides us with the EXPIRE and TTL functions. According to the documentationTTL命令可以用来区分不存在和过期的key:

> SET foo 3
OK
> GET foo
"3"
> EXPIRE foo 5
(integer) 1
> TTL foo
(integer) 3
> TTL foo
(integer) 2
> TTL foo
(integer) 1
> TTL foo
(integer) 0
> TTL foo
(integer) -2

根据 EXPIRE specification,过期对象实际上是在访问时从存储中删除的,或者通过定期随机选择过期键来删除:

Specifically this is what Redis does 10 times per second:

Test 20 random keys from the set of keys with an associated expire.

Delete all the keys found expired.

If more than 25 keys were expired, start again from step 1.

但是 -2(或允许生成它代替 -1 的信息)呢?它是永久保存还是有垃圾收集政策?

另请注意,如果我们为同一个键设置和删除新值,-2 将继续存在:

> SET foo 3
OK
> ttl foo
(integer) -1
> del foo
(integer) 1
> ttl foo
(integer) -2

所以,例如,假设我们有一个脚本,它不断地使用增量名称设置密钥,并使它们在 1 秒后过期。经过任意长时间后,我们会耗尽内存吗?

查看 Redis as a Least-Recently-Used Cache 上的页面 -- 您可以告诉 Redis 不要超过设定的内存量,以及 select 几个密钥过期和清除策略之一。

一个微妙的问题是,并不是 Redis 中的所有数据类型都能很好地处理这个问题,但是带有 ttl set 的集合应该可以。还支持足够的日志记录,以便您跟踪调整时发生的原因和方式。

But what about the -2 (or the information which allows to generate it in place of the -1)? Is it kept forever or is there a garbage collection policy?

-2 表示密钥不在数据库中,例如:

127.0.0.1:6379> flushall
OK
127.0.0.1:6379> ttl somekey
(integer) -2