搞懂Redis RDB和AOF持久化及工作原理

GrimMjx發表於2019-04-13

前言

  因為Redis的資料都儲存在記憶體中,當程式退出時,所有資料都將丟失。為了保證資料安全,Redis支援RDBAOF兩種持久化機制有效避免資料丟失問題。RDB可以看作在某一時刻Redis的快照(snapshot),非常適合災難恢復。AOF則是寫入操作的日誌。本文主要講解RDB、AOF和混合結合使用。

 

一.探索RDB

  RDB就像是一臺給Redis記憶體資料儲存拍照的照相機,生成快照儲存到磁碟的過程。觸發RDB持久化分為手動觸發和自動觸發。Redis重啟讀取RDB速度快,但是無法做到實時持久化,因此一般用於資料冷備複製傳輸

手動觸發

  使用save命令:此命令會使用Redis的主執行緒程式同步儲存,阻塞當前的Redis伺服器,造成服務不可用,直到RDB過程完成。無論當前伺服器資料量大小,線上不要用。

127.0.0.1:6379> save
OK
(1.14s)
59117:M 13 Apr 13:34:51.948 * DB saved on disk

  使用bgsave命令:此命令會通過fork()建立子程式,在後臺程式儲存。只有fork階段會阻塞當前Redis伺服器,不必到整個RDB過程結束,一般時間很短。因此Redis內部涉及到RDB都採用bgsave命令。這裡注意一點,無論RDB還是AOF,由於使用了寫時複製,fork出來的子程式不需要拷貝父程式的實體記憶體空間,但是會複製父程式的空間記憶體頁表。

127.0.0.1:6379> bgsave
Background saving started
59117:M 13 Apr 13:44:40.312 * Background saving started by pid 59180
59180:C 13 Apr 13:44:40.314 * DB saved on disk
59117:M 13 Apr 13:44:40.317 * Background saving terminated with success

自動觸發

  一般我們是不會直接用命令生成RDB檔案的,Redis支援自動觸發RDB持久化機制,配置都在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 ""

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

# 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

# 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 /usr/local/var/db/redis/
  • save m n:代表Redis伺服器在m秒內資料存在n次修改時,自動觸發rdb。這個引數比較關鍵。
  • stop-writes-on-bgsave-error:如果是yes,當bgsave命令失敗時Redis將停止寫入操作。
  • rdbcompression:是否對RDB檔案進行壓縮,但是在LZF壓縮消耗更多CPU
  • rdbchecksum:是否對RDB檔案程式校驗
  • dbfilename:配置檔名稱,預設dump.rdb
  • dir:配置rdb檔案存放的路勁,這個引數比較重要。

工作原理

  首先我們來看一下server.h檔案內saveparams引數,可以看到,seconds就是秒數,changes就是改變數。是不是就對應著剛剛說的save m n的配置呢?

struct redisServer {
    ....
    struct saveparam *saveparams;   /* Save points array for RDB */
    ...
};

struct saveparam {
    time_t seconds;
    int changes;
};

  接下來我們看這個redis.c檔案,有個週期性函式,叫做serverCron,它會週期呼叫,大概做這幾件事情,見註釋。用紅色標註的說明會觸發bgsave和aof rewrite。

/* This is our timer interrupt, called server.hz times per second.
 * Here is where we do a number of things that need to be done asynchronously.
 * For instance:
 *
 * - Active expired keys collection (it is also performed in a lazy way on
 *   lookup).
 * - Software watchdog.
 * - Update some statistic.
 * - Incremental rehashing of the DBs hash tables.
 * - Triggering BGSAVE / AOF rewrite, and handling of terminated children.
 * - Clients timeout of different kinds.
 * - Replication reconnection.
 * - Many more...
 *
 * Everything directly called here will be called server.hz times per second,
 * so in order to throttle execution of things we want to do less frequently
 * a macro is used: run_with_period(milliseconds) { .... }
 */

int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {

  在這個方法裡面有這樣一段程式碼,這邊單獨拿出來,這段程式碼的意思是判斷changes是否滿足並執行save操作。

/* If there is not a background saving/rewrite in progress check if
         * we have to save/rewrite now */
         for (j = 0; j < server.saveparamslen; j++) {
            struct saveparam *sp = server.saveparams+j;

            /* Save if we reached the given amount of changes,
             * the given amount of seconds, and if the latest bgsave was
             * successful or if, in case of an error, at least
             * CONFIG_BGSAVE_RETRY_DELAY seconds already elapsed. */
            if (server.dirty >= sp->changes &&
                server.unixtime-server.lastsave > sp->seconds &&
                (server.unixtime-server.lastbgsave_try >
                 CONFIG_BGSAVE_RETRY_DELAY ||
                 server.lastbgsave_status == C_OK))
            {
                serverLog(LL_NOTICE,"%d changes in %d seconds. Saving...",
                    sp->changes, (int)sp->seconds);
                rdbSaveBackground(server.rdb_filename);
                break;
            }
         }

  接著繼續看這個方法的部分程式碼片段,在rdb.c檔案裡。我們可以看到子程式名為"redis-rdb-bgsave"

int rdbSaveBackground(char *filename) {
    pid_t childpid;
    long long start;

    if (server.aof_child_pid != -1 || server.rdb_child_pid != -1) return C_ERR;

    server.dirty_before_bgsave = server.dirty;
    server.lastbgsave_try = time(NULL);

    start = ustime();
    if ((childpid = fork()) == 0) {
        int retval;

        /* Child */
        closeListeningSockets(0);
        redisSetProcTitle("redis-rdb-bgsave");
        retval = rdbSave(filename);
        if (retval == C_OK) {
            size_t private_dirty = zmalloc_get_private_dirty();

            if (private_dirty) {
                serverLog(LL_NOTICE,
                    "RDB: %zu MB of memory used by copy-on-write",
                    private_dirty/(1024*1024));
            }
        }
        exitFromChild((retval == C_OK) ? 0 : 1);
    }

  最後我們看一下RDB的運作流程圖:

  1. redis執行bgsave命令,Redis判斷當前存在正在進行執行的子程式,如RDB/AOF子程式,存在bgsave命令直接返回
  2. fork出子程式,fork操作中Redis父程式會阻塞
  3. fork完成返回  59117:M 13 Apr 13:44:40.312 * Background saving started by pid 59180
  4. 子程式程式對記憶體資料生成快找檔案
  5. 子程式告訴父程式處理完成

探索RDB檔案

   我們可以使用redis-rdb-tools來分析rdb快照檔案,他可以把rdb快照檔案生成json檔案,看起來比較方便。

rdb -c memory dump.rdb > testMjx.csv

  然後我們看下生成的檔案長啥樣

database,type,key,size_in_bytes,encoding,num_elements,len_largest_element,expiry
0,string,mjx3,56,string,4,4,
0,string,mjx5,56,string,4,4,
0,string,mjx2,56,string,4,4,
0,string,mjx,48,string,8,8,
0,string,mjx4,56,string,4,4,

  生成的資料有database(key在Redis的db)、type(key型別)、key(key值)、size_in_bytes(key的記憶體大小)、encoding(value的儲存編碼形式)、num_elements(key中的value的個數)、len_largest_element(key中的value的長度)、超時時間。

優缺點

  RDB持久化方式的優點:

  • 非常適合全量備份
  • 恢復速度比AOF快

  RDB持久化方式的缺點:

  • RDB方式沒有辦法做到實時持久化
  • 版本相容RDB格式問題

 

二.探索AOF

   RDB方式不能提供強一致性,如果Redis程式崩潰,那麼兩次RDB之間的資料也隨之消失。那麼AOF的出現很好的解決了資料持久化的實時性,AOF以獨立日誌的方式記錄每次寫命令,重啟時再重新執行AOF檔案中的命令來恢復資料。AOF會先把命令追加在AOF緩衝區,然後根據對應策略寫入硬碟(appendfsync),具體引數後面有講。接下來介紹一下AOF重寫命令

手動觸發

  使用bgrewriteaof命令:Redis主程式fork子程式來執行AOF重寫,這個子程式建立新的AOF檔案來儲存重寫結果,防止影響舊檔案。因為fork採用了寫時複製機制,子程式不能訪問在其被建立出來之後產生的新資料。Redis使用“AOF重寫緩衝區”儲存這部分新資料,最後父程式將AOF重寫緩衝區的資料寫入新的AOF檔案中然後使用新AOF檔案替換老檔案。

127.0.0.1:6379> bgrewriteoaf
OK

自動觸發

  和RDB一樣,配置在redis.conf檔案裡,當然你也可以通過呼叫CONFIG SET命令設定。我們先看來看AOF相關配置:

############################## APPEND ONLY MODE ###############################

# By default Redis asynchronously dumps the dataset on disk. This mode is
# good enough in many applications, but an issue with the Redis process or
# a power outage may result into a few minutes of writes lost (depending on
# the configured save points).
#
# The Append Only File is an alternative persistence mode that provides
# much better durability. For instance using the default data fsync policy
# (see later in the config file) Redis can lose just one second of writes in a
# dramatic event like a server power outage, or a single write if something
# wrong with the Redis process itself happens, but the operating system is
# still running correctly.
#
# AOF and RDB persistence can be enabled at the same time without problems.
# If the AOF is enabled on startup Redis will load the AOF, that is the file
# with the better durability guarantees.
#
# Please check http://redis.io/topics/persistence for more information.

appendonly no

# The name of the append only file (default: "appendonly.aof")

appendfilename "appendonly.aof"

# The fsync() call tells the Operating System to actually write data on disk
# instead of waiting for more data in the output buffer. Some OS will really flush
# data on disk, some other OS will just try to do it ASAP.
#
# Redis supports three different modes:
#
# no: don't fsync, just let the OS flush the data when it wants. Faster.
# always: fsync after every write to the append only log. Slow, Safest.
# everysec: fsync only one time every second. Compromise.
#
# The default is "everysec", as that's usually the right compromise between
# speed and data safety. It's up to you to understand if you can relax this to
# "no" that will let the operating system flush the output buffer when
# it wants, for better performances (but if you can live with the idea of
# some data loss consider the default persistence mode that's snapshotting),
# or on the contrary, use "always" that's very slow but a bit safer than
# everysec.
#
# More details please check the following article:
# http://antirez.com/post/redis-persistence-demystified.html
#
# If unsure, use "everysec".

# appendfsync always
appendfsync everysec
# appendfsync no

# When the AOF fsync policy is set to always or everysec, and a background
# saving process (a background save or AOF log background rewriting) is
# performing a lot of I/O against the disk, in some Linux configurations
# Redis may block too long on the fsync() call. Note that there is no fix for
# this currently, as even performing fsync in a different thread will block
# our synchronous write(2) call.
#
# In order to mitigate this problem it's possible to use the following option
# that will prevent fsync() from being called in the main process while a
# BGSAVE or BGREWRITEAOF is in progress.
#
# This means that while another child is saving, the durability of Redis is
# the same as "appendfsync none". In practical terms, this means that it is
# possible to lose up to 30 seconds of log in the worst scenario (with the
# default Linux settings).
#
# If you have latency problems turn this to "yes". Otherwise leave it as
# "no" that is the safest pick from the point of view of durability.

no-appendfsync-on-rewrite no

# Automatic rewrite of the append only file.
# Redis is able to automatically rewrite the log file implicitly calling
# BGREWRITEAOF when the AOF log size grows by the specified percentage.
#
# This is how it works: Redis remembers the size of the AOF file after the
# latest rewrite (if no rewrite has happened since the restart, the size of
# the AOF at startup is used).
#
# This base size is compared to the current size. If the current size is
# bigger than the specified percentage, the rewrite is triggered. Also
# you need to specify a minimal size for the AOF file to be rewritten, this
# is useful to avoid rewriting the AOF file even if the percentage increase
# is reached but it is still pretty small.
#
# Specify a percentage of zero in order to disable the automatic AOF
# rewrite feature.

auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb

# An AOF file may be found to be truncated at the end during the Redis
# startup process, when the AOF data gets loaded back into memory.
# This may happen when the system where Redis is running
# crashes, especially when an ext4 filesystem is mounted without the
# data=ordered option (however this can't happen when Redis itself
# crashes or aborts but the operating system still works correctly).
#
# Redis can either exit with an error when this happens, or load as much
# data as possible (the default now) and start if the AOF file is found
# to be truncated at the end. The following option controls this behavior.
#
# If aof-load-truncated is set to yes, a truncated AOF file is loaded and
# the Redis server starts emitting a log to inform the user of the event.
# Otherwise if the option is set to no, the server aborts with an error
# and refuses to start. When the option is set to no, the user requires
# to fix the AOF file using the "redis-check-aof" utility before to restart
# the server.
#
# Note that if the AOF file will be found to be corrupted in the middle
# the server will still exit with an error. This option only applies when
# Redis will try to read more data from the AOF file but not enough bytes
# will be found.
aof-load-truncated yes

# When rewriting the AOF file, Redis is able to use an RDB preamble in the
# AOF file for faster rewrites and recoveries. When this option is turned
# on the rewritten AOF file is composed of two different stanzas:
#
#   [RDB file][AOF tail]
#
# When loading Redis recognizes that the AOF file starts with the "REDIS"
# string and loads the prefixed RDB file, and continues loading the AOF
# tail.
#
# This is currently turned off by default in order to avoid the surprise
# of a format change, but will at some point be used as the default.
aof-use-rdb-preamble no
  • appendonly:是否開啟AOF持久化功能
  • appendfilename:AOF檔名稱
  • appendfsync:同步頻率
  • auto-aof-rewrite-min-size:如果檔案大小小於此值不會觸發AOF,預設64MB
  • auto-aof-rewrite-percentage:Redis記錄最近的一次AOF操作的檔案大小,如果當前AOF檔案大小增長超過這個百分比則觸發一次重寫,預設100

  這裡介紹一下appendfsync引數的可配置值

  • always:命令寫入aof緩衝區後,每一次寫入都需要同步,直到寫入磁碟(阻塞,系統呼叫fsync)結束後返回。顯然和Redis高效能背道而馳,不建議配置
  • everysec:命令寫入aof緩衝區後,在寫入系統緩衝區直接返回(系統呼叫write),然後有專門執行緒每秒執行寫入磁碟(阻塞,系統呼叫fsync)後返回
  • no:命令寫入aof緩衝區後,在寫入系統緩衝區直接返回(系統呼叫write)。之後寫入磁碟(阻塞,系統呼叫fsync)的操作由作業系統負責,通常最長30s

工作原理

  這裡看一段aof.c的程式碼,我們可以看到fork出名為"redis-aof-rewrite"的子程式

/* This is how rewriting of the append only file in background works:
 *
 * 1) The user calls BGREWRITEAOF
 * 2) Redis calls this function, that forks():
 *    2a) the child rewrite the append only file in a temp file.
 *    2b) the parent accumulates differences in server.aof_rewrite_buf.
 * 3) When the child finished '2a' exists.
 * 4) The parent will trap the exit code, if it's OK, will append the
 *    data accumulated into server.aof_rewrite_buf into the temp file, and
 *    finally will rename(2) the temp file in the actual file name.
 *    The the new file is reopened as the new append only file. Profit!
 */
int rewriteAppendOnlyFileBackground(void) {
    pid_t childpid;
    long long start;

    if (server.aof_child_pid != -1 || server.rdb_child_pid != -1) return C_ERR;
    if (aofCreatePipes() != C_OK) return C_ERR;
    start = ustime();
    if ((childpid = fork()) == 0) {
        char tmpfile[256];

        /* Child */
        closeListeningSockets(0);
        redisSetProcTitle("redis-aof-rewrite");
        snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
        if (rewriteAppendOnlyFile(tmpfile) == C_OK) {
            size_t private_dirty = zmalloc_get_private_dirty();

            if (private_dirty) {
                serverLog(LL_NOTICE,
                    "AOF rewrite: %zu MB of memory used by copy-on-write",
                    private_dirty/(1024*1024));
            }
            exitFromChild(0);
        } else {
            exitFromChild(1);
        }
    }
...
...

  同樣我們也看一下AOF的運作流程圖:

  1. 所有的寫入命令追加到aof緩衝區
  2. AOF緩衝區根據對應appendfsync配置向硬碟做同步操作
  3. 定期對AOF檔案進行重寫
  4. Redis重啟時,可以載入AOF檔案進行資料恢復

探索AOF檔案

  首先開啟aof功能

127.0.0.1:6379> CONFIG SET appendonly yes
OK

59117:M 13 Apr 19:24:53.940 * Background append only file rewriting started by pid 59895
59117:M 13 Apr 19:24:53.964 * AOF rewrite child asks to stop sending diffs.
59895:C 13 Apr 19:24:53.965 * Parent agreed to stop sending diffs. Finalizing AOF...
59895:C 13 Apr 19:24:53.965 * Concatenating 0.00 MB of AOF diff received from parent.
59895:C 13 Apr 19:24:53.966 * SYNC append only file rewrite performed
59117:M 13 Apr 19:24:53.996 * Background AOF rewrite terminated with success
59117:M 13 Apr 19:24:53.996 * Residual parent diff successfully flushed to the rewritten AOF (0.00 MB)
59117:M 13 Apr 19:24:53.997 * Background AOF rewrite finished successfully

  然後我們放一些資料,並執行bgrewriteaof命令

127.0.0.1:6379> CONFIG SET appendonly yes
OK
127.0.0.1:6379> set miao 24
OK
127.0.0.1:6379> set miao 177
OK
127.0.0.1:6379> lpush mlist 1
(integer) 1
127.0.0.1:6379> lpush mlist 2
(integer) 2
127.0.0.1:6379> lpush mlist 3
(integer) 3
127.0.0.1:6379> keys *
1) "miao"
2) "mlist"

  接下來看一下aof檔案:

*2
$6
SELECT
$1
0
*3
$3
SET
$4
miao
$3
177
*2
$6
SELECT
$1
0
*3
$5
lpush
$5
mlist
$1
1
*3
$5
lpush
$5
mlist
$1
2
*3
$5
lpush
$5
mlist
$1
3

  這時候我們手動執行aof重寫命令:

127.0.0.1:6379> bgrewriteaof
Background append only file rewriting started

59117:M 13 Apr 19:29:31.017 * 10 changes in 300 seconds. Saving...
59117:M 13 Apr 19:29:31.017 * Background saving started by pid 59905
59905:C 13 Apr 19:29:31.020 * DB saved on disk
59117:M 13 Apr 19:29:31.120 * Background saving terminated with success
59117:M 13 Apr 19:29:49.409 * Background append only file rewriting started by pid 59906
59117:M 13 Apr 19:29:49.433 * AOF rewrite child asks to stop sending diffs.
59906:C 13 Apr 19:29:49.433 * Parent agreed to stop sending diffs. Finalizing AOF...
59906:C 13 Apr 19:29:49.434 * Concatenating 0.00 MB of AOF diff received from parent.
59906:C 13 Apr 19:29:49.434 * SYNC append only file rewrite performed
59117:M 13 Apr 19:29:49.533 * Background AOF rewrite terminated with success
59117:M 13 Apr 19:29:49.533 * Residual parent diff successfully flushed to the rewritten AOF (0.00 MB)
59117:M 13 Apr 19:29:49.534 * Background AOF rewrite finished successfully

  然後再看一下檔案:

*2
$6
SELECT
$1
0
*3
$3
SET
$4
miao
$3
177
*5
$5
RPUSH
$5
mlist
$1
3
$1
2
$1
1

  為什麼AOF檔案會變小?為了解決AOF檔案會越來越大,Redis引入重寫機制來縮小檔案體積,體積變小因為:

  • 多條寫入命令可以合併成一條。比如上面的lpush命令了3次,最後合併成1條
  • 重寫後AOF檔案只保留最終資料的寫入命令

優缺點

  AOF持久化方式的優點:

  • 做到最多丟失1-2s內的資料(最多丟失2s資料,因為AOF追加阻塞

  AOF持久化方式的缺點:

  • AOF檔案比RDB檔案大
  • 可能導致追加阻塞

 

參考:

書籍參考和上文一樣

https://www.cnblogs.com/huangxincheng/p/5010795.html

相關文章