美文网首页
redis过期策略

redis过期策略

作者: sunpy | 来源:发表于2020-05-28 21:38 被阅读0次

redis设置过期时间

127.0.0.1:6380> set v1 123
OK
127.0.0.1:6380> EXPIRE v1 1000
(integer) 1
127.0.0.1:6380> get v1
"123"

EXPIRE <KEY> <TTL> 将KEY设置生存时间为TTL秒
PEXPIRE <KEY> <TTL> 将KEY设置生存时间为TTL毫秒

查看剩余过期时间

// 返回秒
127.0.0.1:6380> TTL v1
(integer) 810
// 返回毫秒
127.0.0.1:6380> PTTL v1
(integer) 798886

移除过期时间

127.0.0.1:6380> PERSIST v1
(integer) 1
127.0.0.1:6380> TTL v1
(integer) -1

过期策略

redis的过期策略采用定期删除+惰性删除

定期删除

定期删除操作:redis默认配置每隔100毫秒随机抽取一些设置过期时间的key,发现过期就删除。该操作是一种主动操作。

# By default "hz" is set to 10. Raising the value will use more CPU when
# Redis is idle, but at the same time will make Redis more responsive when
# there are many keys expiring at the same time, and timeouts may be
# handled with more precision.
#
# The range is between 1 and 500, however a value over 100 is usually not
# a good idea. Most users should use the default of 10 and raise this up to
# 100 only in environments where very low latency is required.
hz 10

hz 10:表示1s执行10次定期删除操作,默认配置。

# The default of 5 produces good enough results. 10 Approximates very closely
# true LRU but costs a bit more CPU. 3 is very fast but not very accurate.
#
maxmemory-samples 5

maxmemory-samples 5 :随机抽取5个样本,抽样为10将会更接近LRU算法,但是将占用更多的CPU,抽样为3是速度最快的,但是却不是非常准确(就是样本代表全体不准确)。

惰性删除

惰性删除操作:就是客户端在获取某个指定的key时,先去检查当前的key是否过期,过期就直接删除不返回,没过期就直接返回给客户端。

快照持久化对于过期键的操作

快照持久化对过期键没有影响:
当服务器以Master方式运行,那么载入RDB文件,将忽略过期键,只载入为过期键。

127.0.0.1:6380> SET v1 1
OK
127.0.0.1:6380> SET v2 2
OK
127.0.0.1:6380> SET v3 3
OK
127.0.0.1:6380> EXPIRE v3 5
(integer) 1
127.0.0.1:6380> get v3
(nil)
127.0.0.1:6380> SAVE
OK

解析dump.rdb:

D:\rdb-tools\redis-rdb-tools-master\rdbtools\cli>rdb.py --command json C:\Users\
Administrator\Desktop\dump.rdb
WARNING: python-lzf package NOT detected. Parsing dump file will be very slow un
less you install it. To install, run the following command:

pip install python-lzf

[{
"v1":"1",
"v2":"2"}]
D:\rdb-tools\redis-rdb-tools-master\rdbtools\cli>rdb.py --command json C:\Users\
Administrator\Desktop\dump.rdb
WARNING: python-lzf package NOT detected. Parsing dump file will be very slow un
less you install it. To install, run the following command:

pip install python-lzf

[{
"v1":"1",
"v2":"2"}]

当服务器以Slave方式运行,那么就全都载入服务器,当Master服务器数据同步的时候,将Slave数据库清空。

AOF持久化对于过期键的操作

如果发现键已经过期,那么直接往AOF文件中追加一条DEL命令。

127.0.0.1:6380> SET v1 1
OK
127.0.0.1:6380> SET v2 2
OK
127.0.0.1:6380> SET v3 3
OK
127.0.0.1:6380> EXPIRE v2 5
(integer) 1
127.0.0.1:6380> GET v2
(nil)

查看appendonly.aof文件:

DEL
$2
v2

相关文章

网友评论

      本文标题:redis过期策略

      本文链接:https://www.haomeiwen.com/subject/yutgahtx.html