熟悉 Redis 吗,那 Redis 的过期键删除策略是什么?
共 7301字,需浏览 15分钟
·
2024-06-18 08:00
阅读本文大概需要 5.5 分钟。
来自:blog.csdn.net/hdgaadd/article/details/138577716
1. Redis数据库
1.1 Redis数据库的理解
面试官:Redis的数据库知道吧?
# 示例命令
127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> set name JavaGetOffer
OK
127.0.0.1:6379[1]> select 2
OK
127.0.0.1:6379[2]> get name
(nil)
127.0.0.1:6379[2]> select 1
OK
127.0.0.1:6379[1]> get name
"JavaGetOffer"
# 查询一共有几个数据库
127.0.0.1:6379> config get databases
1) "databases"
2) "16"
1.2 数据库的键空间
面试官:那数据库的键空间呢?
1.3 键过期时间
面试官:一个键要怎么设置过期时间?
127.0.0.1:6379> set name0 JavaOffer训练营
OK
127.0.0.1:6379> expire name0 66
(integer) 1
127.0.0.1:6379> ttl name0
(integer) 66
127.0.0.1:6379> get name0
"JavaOffer训练营"
127.0.0.1:6379> setex name 66 JavaGetOffer
OK
127.0.0.1:6379> ttl name
(integer) 66
127.0.0.1:6379> get name
"JavaGetOffer"
public String setex(String key, int seconds, String value) {
this.checkIsInMultiOrPipeline();
this.client.setex(key, seconds, value);
return this.client.getStatusCodeReply();
}
1.4 过期字典
面试官:那键的过期时间知道用什么存储吗?
2. 内存回收策略
2.1 过期键删除策略
面试官:键的过期删除策略是什么?
2.2 内存淘汰策略
面试官:Redis还有什么策略可以释放内存?
127.0.0.1:6379> config set maxmemory 1GB
OK
127.0.0.1:6379> config get maxmemory
1) "maxmemory"
2) "1073741824"
maxmemory-policy
参数来进行控制。
-
noeviction
:默认策略不会删除任何键值对,同时会拒绝所有写命令。 -
volatile-lru
:根据LRU最近最少使用算法删除设置了过期时间的键,直到腾出足够的空间。如果没有可删除的键对象,则会回退到noeviction策略。 -
allkeys-lru
:和volatile-lru同样的作用,不过针对的是所有键。 -
allkeys-random
:随机删除所有键,直到腾出足够的空间。 -
volatile-random
:随机删除过期键,直到腾出足够的空间。 -
volatile-ttl
:删除最近将要过期的键。看到后缀ttl我们就知道这个策略和过期时间相关。
# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached. You can select among five behaviors:
#
# 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.
#
# Note: with any of the above policies, Redis will return an error on write
# operations, when there are no suitable keys for eviction.
#
# At the date of writing these commands are: set setnx setex append
# incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
# sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
# zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
# getset mset msetnx exec sort
#
# The default is:
#
# maxmemory-policy noeviction
推荐阅读:
你了解 localhost 与 127.0.0.1 的区别吗?
《云服务器限时免费领取》 轻量级服务器-2核4G5M 1个月 云服务器-2核4G3M 1个月 ⬇戳阅读原文领取 朕已阅