Home >Database >Mysql Tutorial >redis源代码分析17–持久化之快照

redis源代码分析17–持久化之快照

WBOY
WBOYOriginal
2016-06-07 16:26:361112browse

redis的持久化支持快照方式。快照方式会将整个db dump到磁盘上。 client 可以发布save/bgsave命令让server将db dump到磁盘上。其中bgsave会执行后台dump(新建子进程执行dump),而save是阻塞式的dump db,会影响其他client的命令执行。除了发布命令执行快照

redis的持久化支持快照方式。快照方式会将整个db dump到磁盘上。

client 可以发布save/bgsave命令让server将db dump到磁盘上。其中bgsave会执行后台dump(新建子进程执行dump),而save是阻塞式的dump db,会影响其他client的命令执行。除了发布命令执行快照保存外,redis的serverCron也会按照配置的参数执行后台dump,另外 slave建立连接时,master也会执行一个后台dump,然后才发送数据给slave(这在主从复制一节中介绍)。

static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
    ---
/* Check if a background saving or AOF rewrite in progress terminated */
    if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
      ---
    }
else {
        /* If there is not a background saving in progress check if
         * we have to save now */
         time_t now = time(NULL);
         for (j = 0; j = sp->changes &&
                now-server.lastsave > sp->seconds) {
                redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
                    sp->changes, sp->seconds);
                rdbSaveBackground(server.dbfilename);
                break;
            }
         }
}
---
}

无论是新建子进程还是阻塞式的执行快照方式(新建子进程方式会先调用rdbSaveBackground),最终都会调用rdbSave来保存db。

在rdbSave中可以看到,redis是按type、key、val方式来保存db中的数据的。

rdbLoad是快照方式保存数据后server启动时加载数据的函数,是rdbSave的逆过程。

static int rdbSave(char *filename) {
    ---
    for (j = 0; j type) == -1) goto werr;
          if (rdbSaveStringObject(fp,key) == -1) goto werr;
          if (rdbSaveObject(fp,o) == -1) goto werr;
          ---
        }
        dictReleaseIterator(di);
    }
    ---
    /* Use RENAME to make sure the DB file is changed atomically only
     * if the generate DB file is ok. */
    if (rename(tmpfile,filename) == -1) {
        redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
        unlink(tmpfile);
        return REDIS_ERR;
    }
    ---
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn