Redis Persistence(持久化):Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候再次加载可以使用,也就是说内存中的数据不持久化断电就会丢失
1.RDB(Redis DataBase) 持久化方式:
- 在指定的时间间隔内将内存中的数据集快照写入磁盘,也就是snapshotting快照,它恢复时是将快照文件直接读到内存;
- Redis会单独创建(fork)一个子进程来进行持久化,会先将数据写入到一个临时文件中,待持久化过程都结束了,再用这个临时文件(dump.rdb)替换上次持久化好的文件。整个过程中,主进程是不进行任何IO操作,确保极高的性能。
(1).snapshotting(快照):
将内存中数据以快照的方式写入到二进制文件中,默认的文件名为dump.rdb,保证数据的备份
- 下面的是从redis的配置文件redis.conf截取的内容,可以通过默认的快照配置触发RDB快照,进行数据备份
################################ SNAPSHOTTING ################################
#
# 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 "" //redis-cli config set save ""命令,动态所有停止RDB保存规则的方法
//下面三个是:默认的快照配置
save 900 1 //900秒内如果超过1个key被修改,则进行备份,生成dump.rdb或者替换上次持久化好的文件
save 300 10 //300秒内如果超过10个key被修改,则进行备份,....
save 60 10000 //60秒内如果超过10000个key被修改,则进行备份,....
- stop-writes-on-bgsave-error yes 即使磁盘、权限等方面存在问题,继续正常工作,对数据完整性和一致性要求不高
# However if you have setup your proper monitoring of the Redis server
# and persistence, you may want to disable this feature so that Redis will
# continue to work as usual even if there are problems with disk,
# permissions, and so forth.
stop-writes-on-bgsave-error yes //表示你不在乎数据不一致或者有其他的手段发现和控制
- rdbcompression yes 对于存储到磁盘的快照,可以设置是否进行压缩存储,默认redis会采用LZF进行压缩
# Compress string objects using LZF when dump .rdb databases?
# For default that's set to 'yes' as it's almost always a win.
# If you want to save some CPU in the saving child set it to 'no' but
# the dataset will likely be bigger if you have compressible values or keys.
rdbcompression yes
- rdbchecksum yes 在存储快照后,还可以让redis使用CRC64算法来进行数据校验
# Since version 5 of RDB a CRC64 checksum is placed at the end of the file.
# This makes the format more resistant to corruption but there is a performance
# hit to pay (around 10%) when saving and loading RDB files, so you can disable it
# for maximum performances.
#
# RDB files created with checksum disabled have a checksum of zero that will
# tell the loading code to skip the check.
rdbchecksum yes
(2).常用操作
- save命令:手动迅速备份数据
- bgsave:Redis会在后台异步进行快照操作, 快照同时还可以响应客户端请求, 可以通过lastsave命令获取最后一次成功执行快照的时间
如何恢复数据?
- 将备份文件 (dump.rdb) 移动到 redis 安装目录并启动服务即可
- CONFIG GET dir获取redis 目录
redis 127.0.0.1:6379> CONFIG GET dir
1) "dir"
2) "/usr/local/redis/bin"
2.RDB优点与缺点?
- 优点:适合大规模的数据恢复,对数据完整性和一致性要求不高
- 缺点:在一定间隔时间做一次备份,所以如果redis意外down掉的话,就会丢失最后一次快照后的所有修改;fork的时候,内存中的数据被克隆了一份,大致2倍的膨胀性需要考虑