八、Redis源码持久化之RDB

redis database内存快照

 

一、RDB创建的入口函数和触发时机

源码文件:rdb.c 和 rdb.h

int rdbSaveBackground(char *filename, rdbSaveInfo *rsi); Redis的bgsave命令

int rdbSaveToSlavesSockets(rdbSaveInfo *rsi); Redis执行主从复制命令以及周期性监测主从复制状态触发RDB生成
int rdbSave(char *filename, rdbSaveInfo *rsi); Redis的save命令

除了上面3中时机触发RDB生成外,还有哪些?

rdbSave还会在flushallCommand函数(在db.c文件中)、prepareForShutdown函数(在server.c文件中)中被调用,所以Redis在执行flushall命令以及正常关闭时也会触发创建RDB文件。

 

二、RDB文件结构

文件头:Redis的魔数、RDB版本、Redis版本、RDB文件创建时间、键值对占用的内存大小

文件数据部分:实际的所有键值对数据

文件尾:文件结束符、文件的校验值(redis server加载rdb文件后,检查文件是否被篡改过)

RDB文件生成的核心函数是rdbSaveRio函数,这里我就不做过多的分析了。

 

三、RDB核心参数配置

################################ SNAPSHOTTING  ################################
#
# Save the DB on disk:
#   save <seconds> <changes>
#   In the example below the behaviour will be to save:
#   after 900 sec (15 min) if at least 1 key changed 900秒内有一个变更
#   after 300 sec (5 min) if at least 10 keys changed
#   after 60 sec if at least 10000 keys changed

save 900 1
save 300 10
save 60 10000

# By default Redis will stop accepting writes if RDB snapshots are enabled
# (at least one save point) and the latest background save failed.
# This will make the user aware (in a hard way) that data is not persisting
# on disk properly, otherwise chances are that no one will notice and some
# disaster will happen.
#
# If the background saving process will start working again Redis will
# automatically allow writes again.
#
# 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 创建新的后台进程建rdb文件

# 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 数据压缩

# 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 默认值是yes。在存储快照后,我们还可以让redis使用CRC64算法来进行数据校验,但是这样做会增加大约10%的性能消耗,如果希望获取到最大的性能提升,可以关闭此功能。

# The filename where to dump the DB 快照文件名
dbfilename dump.rdb

# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name. 快照文件存放目录
dir ./

 

posted @ 2022-05-16 00:03  chch213  阅读(48)  评论(0编辑  收藏  举报