Redis的数据持久化方式有 RDB 和 AOF 两种,这篇文章将会讲解 AOF

AOF是什么

AOF(Append Only File)以日志形式记录服务器收到的每一个写操作

AOF怎么进行持久化

使用AOF默认会在当前目录下生成一个 appendonly.aof 日志文件

在恢复数据时,AOF会将appendonly.aof中记录下的所有写操作重新按顺序执行一遍

以下是appendonly.aof文件的示例片段

*2
$6
SELECT
$1
0
*3
$3
SET
$2
id
$3
123
*3
$3
SET
$4
name
$6
DangHT
*3
$3
SET
$4
from
$3
NPU

如果一不小心执行了 FLUSHALL 命令清除了数据集,若想要恢复,可以打开aof文件删除其中的FLUSHALL命令记录即可

AOF有三种触发写入磁盘操作的策略:

AOF与RDB能共存吗

当然可以,然而Redis再数据恢复时会优先去查看AOF文件

当共存时,若AOF文件出错,则Redis服务启动时会报错

官方提供了redis-check-aof命令来自动修复AOF文件(对应的也有redis-check-rdb)

AOF重写(rewrite)机制

AOF采用文件追加方式记录写操作日志,为避免文件越来越大,新增了重写机制,当AOF文件的大小超过所设定的阈值时,Redis就会启动AOF文件的内容压缩,只保留可以恢复数据的最小指令集。使用bgrewriteaof执行重写操作

AOF文件持续增长而过大时,会fork出一条新的子进程来将文件重写(与RDB快照类似,也是先写临时文件最后再rename覆盖),遍历新进程的内存中的数据,每条记录有一条SET语句。重写AOF文件的操作,并没有读取旧的AOF文件,而是将整个内存中的数据库内容用命令的方式重写了一个新的AOF文件。

触发机制:Redis会记录上一次重写时的AOF大小,默认设置是当AOF文件大小是上一次rewrite后大小的一倍且文件大于64M时触发

# 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

AOF的优势

AOF的劣势

赞 赏
真诚赞赏 手有余香
用微信请DangHT喝杯咖啡?

微信支付

用支付宝请DangHT喝杯咖啡?

支付宝