Redis 缓存替换策略
Redis 缓存替换策略
本文分析 redis 的 8 种缓存替换(淘汰)策略
Redis 配置文件
# volatile-lru -> Evict using approximated LRU among the keys with an expire set.
# allkeys-lru -> Evict any key using approximated LRU.
# volatile-lfu -> Evict using approximated LFU among the keys with an expire set.
# allkeys-lfu -> Evict any key using approximated LFU.
# volatile-random -> Remove a random key among the ones with an expire set.
# allkeys-random -> Remove a random key, any key.
# volatile-ttl -> Remove the key with the nearest expire time (minor TTL)
# noeviction -> Don't evict anything, just return an error on write operations.
#
# LRU means Least Recently Used
# LFU means Least Frequently Used
#
# Both LRU, LFU and volatile-ttl are implemented using approximated
# randomized algorithms.
#
#
# The default is:
#
# maxmemory-policy noeviction
# LRU, LFU and minimal TTL algorithms are not precise algorithms but approximated
# algorithms (in order to save memory), so you can tune it for speed or
# accuracy. For default Redis will check five keys and pick the one that was
# used less recently, you can change the sample size using the following
# configuration directive.
#
# The default of 5 produces good enough results. 10 Approximates very closely
# true LRU but costs more CPU. 3 is faster but not very accurate.
#
# maxmemory-samples 5
redis 缓存替换策略分析
基础
LRU:Least Recently Used,最近最少(被)使用,选择最近使用的页面予以保留,反之予以淘汰。该算法赋予每个样本一个访问时间字段,用来记录一个上次被访问的时间戳 t,当必须淘汰一个样本时,选择样本中 t 值最小的予以淘汰。
LFU:Least Frequently Used,最不经常(被)使用,淘汰引用计数最小的样本。算法为每个key维护一个引用计数器,每当key被访问的时候,计数器增大;计数器越大,可以约等于访问越频繁。
分析
class 1, volatile # 基于过期时间的淘汰策略
volatile-lru # 在设置了过期时间的key上,执行LRU策略
volatile-lfu # 在设置了过期时间的key上,执行LFU策略
volatile-random # 在设置了过期时间的key上,执行随机淘汰策略
volatile-ttl # 删除过期时间最近的key
class 2, allkey # 简单过期策略
allkeys-lru # 使用近似LRU策略来淘汰key
allkeys-lfu # 使用近似LFU策略来淘汰key
allkeys-random # 随机淘汰任何key
class 3, no eviction # 不淘汰策略
noeviction # 不淘汰任何key
redis默认使用noeviction策略,也即不淘汰任何的key。
默认情况下,Redis将检查5个key,并选择最近使用较少的1个key进行淘汰。默认值5会产生足够好的结果。10非常接近真实的LRU,但需要更多的CPU。3更快,但不是很准确。
智慧在街市上呼喊,在宽阔处发声。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2017-05-24 中文分词实验总结