redis缓存是支持数据持久化的操做,也就是能够把内存中的数据持久化到硬盘当中,和数据库有些类似,这也是redis和memcache的区别之一。redis
在指定的时间间隔内生成数据集的时间点快照(point-in-time snapshot),也是redis持久化的默认方式。数据库
持久化记录服务器执行的全部操做命令,并在服务启动时,经过从新执行这些命令来还原数据集。缓存
配置以下:安全
<span style="font-size:12px;">################################ SNAPSHOTTING ################################# # # Save the DB on disk: # # save <seconds> <changes> # # Will save the DB if both the given number of seconds and the given # number of write operations against the DB occurred. # # In the example below the behaviour will be to save: # after 900 sec (15 min) if at least 1 key changed # after 300 sec (5 min) if at least 10 keys changed # after 60 sec if at least 10000 keys changed # # Note: you can disable saving at all commenting all the "save" lines. save 900 1 //服务器在900秒内,对缓存数据库至少修改了1次 save 300 10 //服务器在300秒内,对缓存数据库至少修改了1次 save 60 10000 //服务在60秒内,对缓存数据库至少修改了10000次 # Compress string objects using LZF when dump .rdb databases? # For default that's set to 'yes' as it's almost always a win. # If you want to save some CPU in the saving child set it to 'no' but # the dataset will likely be bigger if you have compressible values or keys. rdbcompression yes # 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. # # Also the Append Only File will be created inside this directory. # # Note that you must specify a directory here, not a file name. dir ./ //存到磁盘的路径</span>
只要知足上面三个save配置中的一个,redis就会自动进行数据快照,持久化到硬盘中。用户可根据本身需求进行配置。服务器
看到上面的配置我会很好奇,服务器怎么知道我在多长的时间对缓存数据修改了多少次了?后来发现Redis服务其中有个dirty和一个lastsave时间戳。app
当服务器执行一个数据修改命令以后,dirty计数器数值会进行更新。ide
lastsave则是记录上次服务器执行BGSAVE命令的时间,在这就不详细解释了。this
AOF持久化数据是经过保存Redis服务全部的操做命令,下次启动服务时,重新执行这些操做命令来还原缓存数据。spa
AOF文件刷新有三种方式:code
1.appendfsync always - 每提交一个修改命令都调用fsync刷新到AOF文件,很是很是慢,但也很是安全
2.appendfsync everysec - 每秒钟都调用fsync刷新到AOF文件,很快,但可能会丢失一秒之内的数据
3.appendfsync no - 依靠OS进行刷新,redis不主动刷新AOF,这样最快,但安全性就差
默认并推荐每秒刷新,这样在速度和安全上都作到了兼顾
RDB
RDB恢复数据的方式没有专门的操做命令去执行,redis服务启动时,会自动查找RDB文件进行加载,指导RDB文件加载完成为止。
AOF
服务器在启动时,经过载入和执行AOF文件中保存的命令来还原服务器关闭以前的数据库状态,具体过程:
(1)载入AOF文件
(2)建立模拟客户端
(3)从AOF文件中读取一条命令
(4)使用模拟客户端执行命令
(5)循环读取并执行命令,直到所有完成
若是同时启用了RDB和AOF方式,AOF优先,启动时只加载AOF文件恢复数据