摘要:
分析redis配置中的save, 具体是以何种规则来触发生成rdb.
redis配置中的注释:
#
# Save the DB on disk:
#
# save <seconds> <changes>
#
# Will save the DB if both the given number of seconds and the given
# number of write operations against the DB occurred.
#
# In the example below the behaviour will be to save:
# after 900 sec (15 min) if at least 1 key changed
# after 300 sec (5 min) if at least 10 keys changed
# after 60 sec if at least 10000 keys changed
#
# Note: you can disable saving completely by commenting out all "save" lines.
#
# It is also possible to remove all the previously configured save
# points by adding a save directive with a single empty string argument
# like in the following example:
#
# save ""
save 900 1
save 300 10
save 60 10000
解释下:
save后边有两个参数:
- 第一个参数是以秒为单位的周期
- 第二个参数是该周期内key的变动次数
如果在该周期到达时, key的变动次数达到第二个配置参数的值, 则触发rdb生成.
否则开始新的周期, 上个周期内变动的key的数量, 算作新周期内key的数量.
比如:
设置 save 5 3
以5秒为周期, key的变动次数为3.
- 第一个5秒的周期, 设置了2个key, 那么不会触发rdb生成.
- 随后的5秒的 周期内, 因为上一个周期没有生成rdb, 所以上一个统计周期的key的变动次数2, 记录进本周期. 本周期只要有1个key变动, 则触发rdb生成
测试:
配置 save 5 3
测试脚本:
#!/bin/bash
RDB=./7000/dump.rdb
echo du -b $RDB
du -b $RDB
echo redis-cli -p 7000 set k1 v1
redis-cli -p 7000 set k1 v1
echo redis-cli -p 7000 set k2 v2
redis-cli -p 7000 set k2 v2
echo du -b $RDB
du -b $RDB
echo sleep 7s
sleep 7s
echo du -b $RDB
du -b $RDB
echo redis-cli -p 7000 set k3 v3
redis-cli -p 7000 set k3 v3
echo du -b $RDB
du -b $RDB
echo sleep 1s
sleep 1s
echo du -b $RDB
du -b $RDB
echo '------------------------------'
echo redis-cli -p 7000 set k4 v4
redis-cli -p 7000 set k4 v4
echo redis-cli -p 7000 set k5 v5
redis-cli -p 7000 set k5 v5
echo du -b $RDB
du -b $RDB
echo sleep 1s
sleep 1s
echo du -b $RDB
du -b $RDB
echo redis-cli -p 7000 set k6 v6
redis-cli -p 7000 set k6 v6
echo du -b $RDB
du -b $RDB
echo sleep 1s
sleep 1s
echo du -b $RDB
du -b $RDB
echo sleep 3s
sleep 3s
echo du -b $RDB
du -b $RDB
执行结果:
du -b ./7000/dump.rdb
176 ./7000/dump.rdb
redis-cli -p 7000 set k1 v1
OK
redis-cli -p 7000 set k2 v2
OK
du -b ./7000/dump.rdb
176 ./7000/dump.rdb
sleep 7s
du -b ./7000/dump.rdb
176 ./7000/dump.rdb
redis-cli -p 7000 set k3 v3
OK
du -b ./7000/dump.rdb
176 ./7000/dump.rdb
sleep 1s
du -b ./7000/dump.rdb
202 ./7000/dump.rdb
------------------------------
redis-cli -p 7000 set k4 v4
OK
redis-cli -p 7000 set k5 v5
OK
du -b ./7000/dump.rdb
202 ./7000/dump.rdb
sleep 1s
du -b ./7000/dump.rdb
202 ./7000/dump.rdb
redis-cli -p 7000 set k6 v6
OK
du -b ./7000/dump.rdb
202 ./7000/dump.rdb
sleep 1s
du -b ./7000/dump.rdb
202 ./7000/dump.rdb
sleep 3s
du -b ./7000/dump.rdb
224 ./7000/dump.rdb
结论:
- save配置的时间周期内, 如果key变动数量没到达, 则进入下一个周期累计
- 如果save配置的时间周期内, key的变动数量到达, 但是没到达时间周期, 依然不会触发rdb生成. 必须要等到周期结束的时间点才会生成.