Redis 持久化

持久化概念

持久化是将程序数据在持久状态和瞬时状态间转换的机制。通俗的讲,就是瞬时数据(比如内存中的数据,是不能永久保存的)持久化为持久数据(比如持久化至数据库中,能够长久保存)。

Redis持久化

官方说明:http://www.redis.io/topics/persistence

持久化方式

RDB (Redis Database) 

AOF (Append-only File)

RDB 

Snapshotting

By default Redis saves snapshots of the dataset on disk, in a binary file called dump.rdb. You can configure Redis to have it save the dataset every N seconds if there are at least M changes in the dataset, or you can manually call the SAVE or BGSAVE commands.

For example, this configuration will make Redis automatically dump the dataset to disk every 60 seconds if at least 1000 keys changed:

save 60 1000

默认Redis保存数据集快照到硬盘,二进制文件名为dump.rdb。

保存数据集

设置

    /etc/redis/6379.conf

save 900 1
save 300 10
save 60 10000

  只要满足一个条件就自动执行,配置文件是异步执行BGSAVE。

命令

  SAVE -
  summary: Synchronously save the dataset to disk
  since: 1.0.0
  group: server
  BGSAVE -
  summary: Asynchronously save the dataset to disk
  since: 1.0.0
  group: server

SAVE 同步保存,阻塞Redis其他的命令,执行期间客户端不能接收任何请求,不能在生产环境执行

BGSAVE 异步保存,非阻塞,通过fork自进程实现。

恢复数据

1、获取redis安装目录

CONFIG GET dir

2、将dump.rdb文件移动到此目录下。

3、重启服务。

AOF

打开AOF通过修改配置文件:

appendonly yes

配置Redis同步数据到硬盘的频率   fsync写文件数据到硬盘

1、来一条命令进行一次同步 always

2、每一秒同步一次 (建议,默认的处理方式) everysec

3、不进行fsync同步    no

默认配置

appendfsync everysec

如果AOF文件毁坏可通过redis-check-aof工具修复

redis-check-aof  appendonly.aof   修复前要备份文件

重写可以完成对历史指令的精简,精简AOF文件。

1、通过BGREWRITEAOF命令触发重写

2、重写配置:

auto-aof-rewrite-percentage 100      当AOF文件的增量大于起始大小的100%时,进行AOF文件重写
auto-aof-rewrite-min-size 64mb       当AOF文件大于64mb的时候,进行AOF文件重写

默认备份文件存放位置

/var/lib/redis/6379/appendonly.aof

/var/lib/redis/6379/dump.rdb

恢复数据

1、修改配置文件

appendonly yes

2、将appendonly.aof文件放到dir安装目录下。

3、重启Redis,会自动加载appendonly.aof文件内容。

原文地址:https://www.cnblogs.com/one--way/p/5742180.html