redis 数据删除策略和逐出算法的问题小结

2020-06-12 15:00:04王旭

 557 # from the used memory count, so that network problems / resyncs will
 558 # not trigger a loop where keys are evicted, and in turn the output
 559 # buffer of replicas is full with DELs of keys evicted triggering the deletion
 560 # of more keys, and so forth until the database is completely emptied.
 561 #
 562 # In short... if you have replicas attached it is suggested that you set a lower
 563 # limit for maxmemory so that there is some free RAM on the system for replica
 564 # output buffers (but this is not needed if the policy is 'noeviction').
 
将内存使用限制设置为指定的字节。当已达到内存限制Redis将根据所选的逐出策略(请参阅maxmemory策略)尝试删除数据。

如果Redis无法根据逐出策略移除密钥,或者策略设置为“noeviction”,Redis将开始对使用更多内存的命令(如set、LPUSH等)进行错误回复,并将继续回复只读命令,如GET。

当将Redis用作LRU或LFU缓存或设置实例的硬内存限制(使用“noeviction”策略)时,此选项通常很有用。

警告:如果将副本附加到启用maxmemory的实例,则将从已用内存计数中减去馈送副本所需的输出缓冲区的大小,这样,网络问题/重新同步将不会触发收回密钥的循环,而副本的输出缓冲区将充满收回的密钥增量,从而触发删除更多键,依此类推,直到数据库完全清空。

简而言之。。。如果附加了副本,建议您设置maxmemory的下限,以便系统上有一些空闲RAM用于副本输出缓冲区(但如果策略为“noeviction”,则不需要此限制)。

驱逐策略的配置

Maxmemery-policy volatile-lru

当前已用内存超过 maxmemory 限定时,触发主动清理策略

易失数据清理

volatile-lru:只对设置了过期时间的key进行LRU(默认值)

volatile-random:随机删除即将过期key

volatile-ttl : 删除即将过期的

volatile-lfu:挑选最近使用次数最少的数据淘汰

全部数据清理

allkeys-lru : 删除lru算法的key

allkeys-lfu:挑选最近使用次数最少的数据淘汰

allkeys-random:随机删除

禁止驱逐

(Redis 4.0 默认策略)

noeviction : 永不过期,返回错误当mem_used内存已经超过maxmemory的设定,对于所有的读写请求都会触发redis.c/freeMemoryIfNeeded(void)函数以清理超出的内存。注意这个清理过程是阻塞的,直到清理出足够的内存空间。所以如果在达到maxmemory并且调用方还在不断写入的情况下,可能会反复触发主动清理策略,导致请求会有一定的延迟。

清理时会根据用户配置的maxmemory-policy来做适当的清理(一般是LRU或TTL),这里的LRU或TTL策略并不是针对redis的所有key,而是以配置文件中的maxmemory-samples个key作为样本池进行抽样清理。