Redis中的淘汰策略

Redis 的内存淘汰策略,是指当内存使用达到最大内存极限时,需要使用淘汰算法来决定清理掉哪些数据,以保证新数据的存入。

 

最大内存设置

redis.conf 参数配置:

# maxmemory <bytes>

如果不设置maxmemory 或者设置为0,64 位系统不限制内存,32 位系统最多使用3GB 内存。

动态修改:

redis> config set maxmemory 2GB

到达最大内存以后怎么办?

 

淘汰策略

https://redis.io/topics/lru-cache

redis.conf

# maxmemory-policy noeviction

# 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,Least Recently Used:最近最少使用。判断最近被使用的时间,目前最远的数据优先被淘汰。

LFU,Least Frequently Used,最不常用,4.0 版本新增。

random,随机删除。

策略含义
volatile-lru根据LRU 算法删除设置了超时属性(expire)的键,直到腾出足够内存为止。如果没有可删除的键对象,回退到noeviction 策略。
allkeys-lru根据LRU 算法删除键,不管数据有没有设置超时属性,直到腾出足够内存为止。
volatile-lfu在带有过期时间的键中选择最不常用的。
allkeys-lfu在所有的键中选择最不常用的,不管数据有没有设置超时属性。
volatile-random在带有过期时间的键中随机选择。
allkeys-random随机删除所有键,直到腾出足够内存为止。
volatile-ttl根据键值对象的ttl 属性,删除最近将要过期数据。如果没有,回退到noeviction 策略。
noeviction默认策略,不会删除任何数据,拒绝所有写入操作并返回客户端错误信息(error)OOM
command not allowed when used memory,此时Redis 只响应读操作。

 

 

 

 

 

 

 

 

 

 

 

如果没有符合前提条件的key 被淘汰,那么volatile-lru、volatile-random 、volatile-ttl 相当于noeviction(不做内存回收)。

动态修改淘汰策略:

redis> config set maxmemory-policy volatile-lru

建议使用volatile-lru,在保证正常服务的情况下,优先删除最近最少使用的key。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值