Redis从入门到精通四Redis的持久化和数据备份与恢复

3次阅读

共计 7198 个字符,预计需要花费 18 分钟才能阅读完成。

本文将对 Redis 的两种持久化方式做详细的介绍, 从配置, 机制, 优缺点几方面讲起, 最后是关于数据的备份与恢复的介绍。

Redis 持久化简介

Redis 提供了两种持久化的选项, 一种是 快照文件 (snapshotting,RDB), 它会基于某个时间点将数据全部写入硬盘中(默认为dump.rdb)。另一种是 只追加文件(append-only,AOF), 它会在执行写入命令时将命令写入到硬盘中。

Redis 持久化数据最主要是为了 数据备份, 故障恢复, 也有一些经过耗时较长的计算结果存在 Redis 中, 如果这些数据存在硬盘中, 即使服务器重启了之后, 这些数据还是存在的, 不用再去耗时计算了。

这两种方式可以单独使用, 也可以结合起来使用。最重要的还是要理解 RDB 和 AOF 的优劣势,结合自己的应用做一个权衡。

RDB (SNAPSHOTTING)

RDB 配置项

save 900 1
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir ./

上面 6 项配置中, 前 5 项均是 RDB 的配置, 最后一个是RDBAOF 公用的配置

  • dir ./, 指定 RDBAOF 文件的路径
  • save 900 1 , 多久执行一次快照操作, 900 秒内有 1 次写入则执行快照操作
  • stop-writes-on-bgsave-error , 创建快照失败后是否依然写命令, 默认为yes
  • rdbcompression , 是否对快照文件进行压缩, 默认为 yes
  • rdbchecksum , rdb 文件是否启用 CRC64 文件数据完整性检查,5.0 版本之后的属性, 默认为 yes, 开启后在 saveload 时将耗费 10%的性能, 可以关闭此配置来提高性能
  • dbfilename , rdb 文件名, 默认为 dump.rdb

RDB 详解

Redis 通过创建快照的方式, 获得内存中某个时间点的数据副本。Redis 重启时可以从 RDB 文件上恢复数据。我们也可以把 RDB 文件备份在别的服务器上。

根据上述的几个配置项, 快照被写入 dir 目录下的 dbfilename 文件中。如果在新的快照文件创建完成之前,Redis 服务器发生了宕机, 那这期间的数据将丢失。

Redis 中有两个命令可以创建快照文件, SAVEBGSAVE

  • 执行 SAVE 命令后, 服务器将不会再相应任何命令, 直到快照文件完成。
  • 执行 BGSAVE 命令后,Redis 父进程会调用 fork 来创建一个子进程, 由子进程去负责快照文件的写入, 父进程则继续处理客户端的命令请求。
  1. 客户端可以直接向服务器发送 SAVE 或者 BGSAVE
  2. 如果设置了 save 配置项, 达到配置项的要求时,Redis 会自动执行 BGSAVE 命令。该配置项可以设置多组, 如果设置了多组, 只要达到其中一组的要求, 就会执行BGSAVE
  3. Redis 通过SHUTDOWN 指令, 或者接收到标准 TERM 信号时, 会执行 SAVE 命令, 阻塞所有客户端, 直到 SAVE 命令执行完成后, 关闭服务器
  4. Redis 配置了复制集之后, 从服务器向主服务器发来 SYNC 命令, 主服务器会执行 BGSAVE 命令, 然后将快照文件发给从服务器

需要注意的是, 执行 BGSAVE 命令可能会造成服务器暂停几毫秒或者几秒, 具体时长要根据数据量的大小以及服务器的配置来看。在数据量特别大, 服务器内存吃紧的情况下, 可能会造成长时间的停顿, 甚至宕机。通常情况下, BGSAVE 是要比 SAVE 好一些, 因为不会影响客户端的请求, 不过在数据量巨大的情况下, BGSAVE 可能会比 SAVE 指令耗时更长。所以还是要结合具体的数据情况来选择。如果可以接受数据丢失 5 分钟,15 分钟,1 小时甚至更长时间的数据的话, 甚至可以关闭自动保存, 由客户端决定什么时候来执行快照副本的创建。

RDB 优点

  • 冷备份,例如: 可以设置每个小时归档数据集, 并备份至其他服务器, 发生灾难时可以选择恢复数据集的不同副本。
  • 对 Redis 的读写影响小, 最大限度的提高了性能。父进程会 fork 一个子进程区做数据集的归档, 不会影响父进程的工作。
  • 在恢复数据集时,RDB 比 AOF 更加高效

RDB 缺点

  • 在发生灾难的时候,RDB 会比 AOF 丢失的数据多。可以通过设置来更改保存点, 一般设置为 5 分钟。
  • RDB 每次在 fork 子线程来执行 RDB 快照文件时, 如果数据文件特别大且 CPU 性能不佳, 可能造成服务暂停几毫秒或者几秒。

AOF (append-only)

AOF 配置项

appendonly no
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes
  • appendonly, 是否开启 AOF, 默认为 no
  • appendfilename, AOF 文件名
  • appendfsync ① , 多久才将写入的内容同步到硬盘上, 有 always,everysec(默认),no 三种。下面对比了三种方式的性能
  • no-appendfsync-on-rewrite , 在重写时是否执行 fsync 操作, 默认为 no
  • auto-aof-rewrite-percentage ②, 当文件达到上一个文件的多少百分比时自动重写
  • auto-aof-rewrite-min-size ②, 自动重写的最小文件体积
  • aof-load-truncated ③,AOF 文件被截断时是否启动, 默认为 yes
  • aof-use-rdb-preamble ④, 是否支持 AOF 和 RDB 混合使用, 默认为 yes

(1) 关于 appendfsync 的说明

选项 同步频率
always 每次执行写入操作都执行fsync, 这将非常影响性能, 严重降低 Redis 的吞吐
everysec 每隔 1s 执行一次 fsync, 显示的将多个写入命令同步到硬盘, 性能非常好, 如果丢失数据也只是丢失 1s 内的数据
no 不执行 fsync , 交给操作系统去处理。一般 Linux 是每隔 30s 刷新一次数据到磁盘上, 取决于内核的精准调整

(2) 关于 rewrite

前面提到,AOF 是将每条写入命令都同步到硬盘, 包括删除 key 的指令, 一直这么下去,AOF 文件将会变的非常庞大, 甚至占用所有硬盘空间。

rewrite 就是解决这个问题的, 它对应的命令是 BGREWRITEAOF , 这个命令和 BGSAVE 非常相似, 都是由 Redis 父进程 fork 的子进程去执行操作, 所以它和 BGSAVE 有相同的缺点。
BGREWRITEAOF 会通过移除 AOF 中冗余命令的方式来重写 AOF 文件, 重写之后体积就会变小很多。

auto-aof-rewrite-percentageauto-aof-rewrite-min-size 这两项配置是配置自动重写 AOF 文件的触发条件, 只有在设置了 appendonly yes 的情况下, 也就是开启了 AOF 持久化机制才会生效。
举个例子,auto-aof-rewrite-percentage 100, auto-aof-rewrite-min-size 64mb 表示, 当 AOF 大于 64mb 并且比上一次重写之后的体积大了100% 才会执行BGREWRITEAOF。可以通过修改这两项参数来控制 AOF 重写的频率。

(3) 关于 aof-load-truncated

在写入 AOF 文件的过程中, 可能会由于各种原因 (停电, 磁盘空间占满, 服务器故障导致 Redis 宕机) 导致 AOF 写入命令被截断, 如果该配置项设置为 yes , Redis 将会在重启时, 清除被截断的命令之后的所有命令 (通常情况下后面也没有命令了), 然后正常重启。如果不想这样, 可以将此项设置为 no ,Redis 将会在重启时抛出错误并退出。 需要注意的是: 最新版本中即使设置了 no , Redis 也会将被截断的命令之后所有命令删除, 以保证下次重新启动时能够正常启动, 老版本中则不会, 需要使用 redis-check-aof 工具来修复, 具体命令是redis-check-aof --fix

以下是 aof-load-truncated yes 的情况下,Redis 重启时发现了 AOF 被截断, 打出的日志

* Reading RDB preamble from AOF file...
* Reading the remaining AOF tail...
# !!! Warning: short read while loading the AOF file !!!
# !!! Truncating the AOF at offset 439 !!!
# AOF loaded anyway because aof-load-truncated is enabled

(4) 关于 aof-use-rdb-preamble

Redis4.0 以后,支持 AOF 和 RDB 混合使用, 可以通过此项进行配置是否开启。

AOF 详解

AOF 机制对每条写入命令作为日志,以 append-only 的模式写入一个日志文件中,在 redis 重启的时候,可以通过回放 AOF 日志中的写入指令来重新构建整个数据集。
Redis 并不会将数据直接写入硬盘中, 而是会先将数据写进 linux os cache, 然后在通过配置的appendfsync 设置的时间来执行fsync 操作,强行将数据刷入磁盘文件。
AOF 是存放每条的写命令, 所以会不断扩大, 当大到一定程度,AOF 做 rewrite 操作, 就会基于当时 redis 内存中的数据, 来重新构造一个更小的 AOF 文件, 然后将旧的文件删掉。

AOF 优点

  • AOF 可以更好的保护数据不丢失, 一般 AOF 每隔一秒, 通过后台线程执行一次 fsync, 最多丢失 1s 的数据。可以通过设置改为每次写入数据时都执行 fsync,不过这非常影响性能。
  • AOF 日志仅仅时附加日志,如果因为某些原因导致只写入一般,也可以通过redis-check-aof 轻松修复。
  • AOF 日志文件过大时, 会在后台执行 rewrite 操作, 不会影响客户端的读写
  • AOF 日志文件可能性好,因为记录的时一条一条的指令。

AOF 缺点

  • AOF 日志通常比 RDB 数据快照文件更大
  • 做数据恢复的时候可能会比 RDB 慢
  • 做定期的冷备没有 RDB 方便

RDB 和 AOF 文件损坏了

Redis 为我们提供了工具,redis-check-rdbredis-check-aof

具体使用方法如下:

[root@iZnom30el3gvhxZ ~]# redis-check-aof
Usage: redis-check-aof [--fix] <file.aof>
[root@iZnom30el3gvhxZ ~]# redis-check-rdb
Usage: redis-check-rdb <rdb-file-name>

下面是官方文档中对于 AOF 文件损坏的一些说明,我摘了过来:

If the AOF file is not just truncated, but corrupted with invalid byte sequences in the middle, things are more complex. Redis will complain at startup and will abort:

* Reading the remaining AOF tail...
# Bad file format reading the append only file: make a backup of your AOF file, then use ./redis-check-aof --fix <filename>

The best thing to do is to run the redis-check-aof utility, initially without the --fix option, then understand the problem, jump at the given offset in the file, and see if it is possible to manually repair the file: the AOF uses the same format of the Redis protocol and is quite simple to fix manually. Otherwise it is possible to let the utility fix the file for us, but in that case all the AOF portion from the invalid part to the end of the file may be discareded, leading to a massive amount of data lost if the corruption happen to be in the initial part of the file.

How it works

Log rewriting uses the same copy-on-write trick already in use for snapshotting. This is how it works:

  • Redis forks, so now we have a child and a parent process.
  • The child starts writing the new AOF in a temporary file.
  • The parent accumulates all the new changes in an in-memory buffer (but at the same time it writes the new changes in the old append-only file, so if the rewriting fails, we are safe).
  • When the child is done rewriting the file, the parent gets a signal, and appends the in-memory buffer at the end of the file generated by the child.
  • Profit! Now Redis atomically renames the old file into the new one, and starts appending new data into the new file.

How I can switch to AOF, if I’m currently using dump.rdb snapshots?

There is a different procedure to do this in Redis 2.0 and Redis 2.2, as you can guess it’s simpler in Redis 2.2 and does not require a restart at all.

Redis >= 2.2

  • Make a backup of your latest dump.rdb file.
  • Transfer this backup into a safe place.
  • Issue the following two commands:
  • redis-cli config set appendonly yes
  • redis-cli config set save “”
  • Make sure that your database contains the same number of keys it contained.
  • Make sure that writes are appended to the append only file correctly.

The first CONFIG command enables the Append Only File. In order to do so Redis will block to generate the initial dump, then will open the file for writing, and will start appending all the next write queries.

The second CONFIG command is used to turn off snapshotting persistence. This is optional, if you wish you can take both the persistence methods enabled.

IMPORTANT: remember to edit your redis.conf to turn on the AOF, otherwise when you restart the server the configuration changes will be lost and the server will start again with the old configuration.

Redis 2.0

  • Make a backup of your latest dump.rdb file.
  • Transfer this backup into a safe place.
  • Stop all the writes against the database!
  • Issue a redis-cli bgrewriteaof. This will create the append only file.
  • Stop the server when Redis finished generating the AOF dump.
  • Edit redis.conf end enable append only file persistence.
  • Restart the server.
  • Make sure that your database contains the same number of keys it contained.
  • Make sure that writes are appended to the append only file correctly.

RDB 和 AOF 如何选择?

通过以上内容, 应该已经对 RDB 和 AOF 两种方式的优缺点有了大概的了解, 具体如何选择, 还需根据自己的业务情况来选择, 这里给出的意见是两种一起用, 条件允许的话, 将持久化的文件时常备份到多台不同的服务器上。

Redis4.0 以后,支持 AOF 和 RDB 混合使用, 在 redis.conf 中通过 aof-use-rdb-preamble yes 设置。


更多详细内容参考:

Redis 持久化官方文档

Redis 实战

正文完
 0