REDIS AOF文件解析

时间:2025-04-15 07:02:32

一、简述
Redis是内存数据库,所以持久化是必须的,redis提供 RDB 和 AOF 两种持久化方案。

RDB 即 Redis DataBase,文件中存的是数据
AOF 即 Append Only File,文件中存的是写操作命令

对于RDB 而言,已经介绍过,有兴趣的可以阅读【RDB文件解析】。

二、配置
本文主要讲述AOF文件的内容。
AOF模式默认是关闭的,在中,找到 APPEND ONLY MODE内容

# 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 /topics/persistence for more information.

appendonly no #aof模式开关

# The name of the append only file (default: "")
appendfilename "" #aof文件名

......

# If unsure, use "everysec".

# appendfsync always #同步持久化,每次发生数据变化会立刻写入到磁盘
appendfsync everysec #出厂默认推荐,每秒异步记录一次
# appendfsync no #不同步

......

# AOF重写,有效压缩aof文件大小
# 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

三、开启与解析
Windows下开启aof持久化(直接修改是拒绝访问的)

C:\Users\Administrator>redis-cli config set appendonly yes
OK

C:\Users\Administrator>redis-cli config get appendonly
1) "appendonly"
2) "yes"

执行save/bgsave操作,就可以看到文件,内容如下:

*2 			#当前命令有两个参数
$6 			#第一个参数长度是6字节,即SELECT
SELECT 		#当前命令的第一个参数值
$1 			#当前命令的第二个参数,长度是1,即0
0 			#当前命令的第二个参数值
*3
$3
SET
$4
name
$4
jack
*2
$6
SELECT
$1
0
*3
$3
set
$3
sex
$4
male

*N 是命令的参数个数,命令本身也是参数
$M 是参数的长度,即字节数
见以上代码说明

四、综述

  1. Redis 默认开启RDB,在指定的时间间隔内,执行指定次数的写操作,则将内存中的数据写入到磁盘中。
  2. RDB 持久化适合大规模的数据恢复,但数据一致性和完整性较差。
  3. Redis 可手动开启AOF,默认是每秒将写操作日志追加到AOF文件中。
  4. AOF 的数据完整性比RDB高,但文件会越来越大,影响数据恢复效率,针对 AOF文件大问题,提供AOF重写机制(将多个命令操作同一数据的合并为一个命令)。
  5. Redis 做缓存使用时,可关闭持久化。
  6. 若使用Redis 的持久化,建议RDB和AOF都开启。
  7. RDB,AOF同时存在时,优先使用AOF文件