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。