设置最大可用内存

maxmemory 2000mb 

淘汰策略

淘汰策略

策略

noeviction

不淘汰任何数据,内存不足返回错误

volatile-lru

基于lru算法只淘汰带TTL的键

allkeys-lru

基于lru算法淘汰所有键

volatile-random

随机淘汰带TTL的键

allkeys-random

随机淘汰所有键

volatile-ttl

淘汰设置了TTL的键,TTL越小越先淘汰

算法

LRU Least Recently Used

最少最近使用,当前时间减去最后一次访问时间,值越大越先淘汰 LFU Least Frequently Used

最少频率使用,统计key的访问频率,值越小越先淘汰

实践验证

最大内存使用限制2M

maxmemory 2MB

db1 创建不带TTL的键

db2 创建带有TTL的键

127.0.0.1:16379> select 2
OK
127.0.0.1:16379[2]> set num1 "feafafafafaf"
OK
127.0.0.1:16379[2]> set num2 "feaffefeafafafafaf"
OK
127.0.0.1:16379[2]> set num3 "ffafaeaffefeafafafafaf"
OK
127.0.0.1:16379[2]> set num4 "efafafffafaeaffefeafafafafaf"
OK
127.0.0.1:16379[2]> set num5 "efafafffafaeaffefeafafafafaf"
OK
127.0.0.1:16379[2]> expire num1 500
(integer) 1
127.0.0.1:16379[2]> expire num2 600
(integer) 1
127.0.0.1:16379[2]> expire num3 6000
(integer) 1
127.0.0.1:16379[2]> expire num4 2000
(integer) 1
127.0.0.1:16379[2]> expire num5 1000
(integer) 1

写入大量键触发OOM

(error) OOM command not allowed when used memory > 'maxmemory'.
(error) OOM command not allowed when used memory > 'maxmemory'.
(error) OOM command not allowed when used memory > 'maxmemory'.
(error) OOM command not allowed when used memory > 'maxmemory'.

查看db1和db2的数据变化

127.0.0.1:16379[2]> keys *
(empty list or set)
127.0.0.1:16379[1]> keys *
40) "num31"
41) "num16"
42) "num14"
43) "num43"
44) "num44"