咱们知道redis是带有持久化这个能力了,那到底持久化成到哪里,持久化成啥样呢???这篇咱们一块儿来寻求答案。redis
一:快照模式数组
或许在用Redis之初的时候,就据说过redis有两种持久化模式,第一种是SNAPSHOTTING模式,仍是一种是AOF模式,并且在实战场景下用的最多的less
莫过于SNAPSHOTTING模式,这个不须要反驳吧,并且你可能还知道,使用SNAPSHOTTING模式,须要在redis.conf中设置配置参数,好比下面这样:async
# 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 completely by commenting out all "save" lines. # # It is also possible to remove all the previously configured save # points by adding a save directive with a single empty string argument # like in the following example: # # save "" save 900 1 save 300 10 save 60 10000
上面三组命令也是很是好理解的,就是说900指的是“秒数”,1指的是“change次数”,接下来若是在“900s“内有1次更改,那么就执行save保存,一样函数
的道理,若是300s内有10次change,60s内有1w次change,那么也会执行save操做,就这么简单,看了我刚才说了这么几句话,是否是有种直觉在oop
告诉你,有两个问题是否是要澄清一下:字体
1. 上面这个操做应该是redis自身进行的同步操做,请问是否能够手工执行save呢? spa
固然能够进行手工操做,redis提供了两个操做命令:save,bgsave,这两个命令都会强制将数据刷新到硬盘中,以下图:线程
2. 看上面的图,貌似bgsave是开启单独线程的,请问是吗?code
确实如你所说,bgsave是开启次线程进行数据刷新的,不信的话咱们来看看代码,它的代码是在rdb.c源文件中,以下:
从上面的代码中,有没有看到一个重点,那就是fork方法,它就是一些牛人口中说的什么fork出一个线程,今天你也算终于看到了,其实redis并非单纯
的单线程服务,至少fork告诉咱们,它在一些场景下也是会开启工做线程的,而后能够看到代码会在工做线程中执行同步的bgsave操做,就这么简单。
3. 能简单说下saveparams参数在redis源码中的逻辑吗?
能够的,其实在redis中有一个周期性函数,叫作serverCron,它会周期性启动,大概会作七件事情,如redis注释所说:
/* This is our timer interrupt, called server.hz times per second. * Here is where we do a number of things that need to be done asynchronously. * For instance: * * - Active expired keys collection (it is also performed in a lazy way on * lookup). * - Software watchdog. * - Update some statistic. * - Incremental rehashing of the DBs hash tables. * - Triggering BGSAVE / AOF rewrite, and handling of terminated children. * - Clients timeout of different kinds. * - Replication reconnection. * - Many more... * * Everything directly called here will be called server.hz times per second, * so in order to throttle execution of things we want to do less frequently * a macro is used: run_with_period(milliseconds) { .... } */ int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
上面的红色字体就是作了咱们所关心的save操做,看过方法的注释,接下来咱们来找一下具体逻辑。
从上面这段代码逻辑,你应该能够发现如下几点:
<1>. saveparams参数是在server对象下面,而server对象正好是redisServer类型,以下图:
从上面图中 *saveparams 的注释上来看,你应该知道*saveparams是saveparam类型的数组,那如今是否是有强烈的好奇心想看一下saveparam
类型是怎么定义的的呢??? 以下图:
能够看到,saveparam参数里面有两个参数,seconds就是保存秒数,changes就是改变量,而这二个参数就对应着咱们配置文件中的900 0 这样的
配置节,想起来的没有哈~~~
<2> 而后咱们经过if发现,若是终知足,就会最终调用rdbSaveBackground来持久化咱们的rdb文件,简单吧。。。
好了,大概就这样了,但愿对你有帮助。