← 返回首页
Redis持久化之AOF
发表时间:2023-11-14 03:08:55
Redis持久化之AOF

Redis持久化之AOF

1.AOF持久化

AOF持久化是通过日志文件的方式,Redis默认情况下没有开启,可以通过redis.conf的appendonly参数开启。

############################## 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 yes

AOF日志文件的保存位置和RDB文件相同,都是dir参数设置的,默认的文件名是appendonly.aof。

# 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 ./

注意:dir参数的值为. 表示当前目录,也就是说我们在哪个目录下启动redis,rdb快照文件和aof日志文件就产生在哪个目录下。

AOF方式只会记录用户的写命令,添加、修改、删除之类的命令,查询命令不会记录,因为查询命令不会影响数据的内容。那redis什么时候会把用户的写命令同步到aof文件中呢?

# appendfsync always
appendfsync everysec
# appendfsync no

默认是每秒钟执行一次同步操作。appendfsync everysec 也可以实现每执行一次写操作就执行一次同步操作,appendfsync always,但是这样效率会有点低。 或者使用appendfsync no,表示不主动进行同步,由操作系统来做,默认30秒执行一次。

如果大家对数据的丢失确实是0容忍的话,可以使用always。不过一般情况下,redis中存储的都是一些缓存数据,就算丢了也没关系,程序还会继续往里面写新数据,不会造成太大的影响。

注意:如果同时开启AOF持久化和RDB持久化,那么redis认为AOF持久化的数据是最完整的。因此会丢失原来RDB里保存的数据。我们可以在RDB模式下先临时开启AOF持久化,这样在重新启动Redsi之后,AOF里会保存原来RDB里的数据。

127.0.0.1:6379> config set appendonly yes
ok