Redis數據持久化機制AOF原理分析二

分類: Redis 2014-01-12 15:36  737人閱讀  評論(0)  收藏  舉報

目錄(?)[+] html

本文所引用的源碼所有來自Redis2.8.2版本。 ios

Redis AOF數據持久化機制的實現相關代碼是redis.c, redis.h, aof.c, bio.c, rio.c, config.c redis

在閱讀本文以前請先閱讀Redis數據持久化機制AOF原理分析之配置詳解文章,瞭解AOF相關參數的解析,文章連接 數據庫

http://blog.csdn.net/acceptedxukai/article/details/18135219 服務器

接着上一篇文章,本文將介紹Redis是如何實現AOF rewrite的。 app

轉載請註明,文章出自http://blog.csdn.net/acceptedxukai/article/details/18181563 ide


AOF rewrite的觸發機制


若是Redis只是將客戶端修改數據庫的指令重現存儲在AOF文件中,那麼AOF文件的大小會不斷的增長,由於AOF文件只是簡單的重現存儲了客戶端的指令,而並無進行合併。對於該問題最簡單的處理方式,即當AOF文件知足必定條件時就對AOF進行rewrite,rewrite是根據當前內存數據庫中的數據進行遍歷寫到一個臨時的AOF文件,待寫完後替換掉原來的AOF文件便可。 函數


Redis觸發AOF rewrite機制有三種: 網站

一、Redis Server接收到客戶端發送的BGREWRITEAOF指令請求,若是當前AOF/RDB數據持久化沒有在執行,那麼執行,反之,等當前AOF/RDB數據持久化結束後執行AOF rewrite this

二、在Redis配置文件redis.conf中,用戶設置了auto-aof-rewrite-percentage和auto-aof-rewrite-min-size參數,而且當前AOF文件大小server.aof_current_size大於auto-aof-rewrite-min-size(server.aof_rewrite_min_size),同時AOF文件大小的增加率大於auto-aof-rewrite-percentage(server.aof_rewrite_perc)時,會自動觸發AOF rewrite

三、用戶設置「config set appendonly yes」開啓AOF的時,調用startAppendOnly函數會觸發rewrite

下面分別介紹上述三種機制的處理.


接收到BGREWRITEAOF指令


  1. <span style="font-size:12px;">void bgrewriteaofCommand(redisClient *c) {  
  2.     //AOF rewrite正在執行,那麼直接返回  
  3.     if (server.aof_child_pid != -1) {  
  4.         addReplyError(c,"Background append only file rewriting already in progress");  
  5.     } else if (server.rdb_child_pid != -1) {  
  6.         //AOF rewrite未執行,但RDB數據持久化正在執行,那麼設置AOF rewrite狀態爲scheduled  
  7.         //待RDB結束後執行AOF rewrite  
  8.         server.aof_rewrite_scheduled = 1;  
  9.         addReplyStatus(c,"Background append only file rewriting scheduled");  
  10.     } else if (rewriteAppendOnlyFileBackground() == REDIS_OK) {  
  11.         //直接執行AOF rewrite  
  12.         addReplyStatus(c,"Background append only file rewriting started");  
  13.     } else {  
  14.         addReply(c,shared.err);  
  15.     }  
  16. }</span>  
當AOF rewrite請求被掛起時,在serverCron函數中,會處理。
  1. /* Start a scheduled AOF rewrite if this was requested by the user while 
  2.      * a BGSAVE was in progress. */  
  3.     // 若是用戶執行 BGREWRITEAOF 命令的話,在後臺開始 AOF 重寫  
  4.     //當用戶執行BGREWRITEAOF命令時,若是RDB文件正在寫,那麼將server.aof_rewrite_scheduled標記爲1  
  5.     //當RDB文件寫完後開啓AOF rewrite  
  6.     if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 &&  
  7.         server.aof_rewrite_scheduled)  
  8.     {  
  9.         rewriteAppendOnlyFileBackground();  
  10.     }  


Server自動對AOF進行rewrite

在serverCron函數中會週期性判斷
  1. /* Trigger an AOF rewrite if needed */  
  2.          //知足必定條件rewrite AOF文件  
  3.          if (server.rdb_child_pid == -1 &&  
  4.              server.aof_child_pid == -1 &&  
  5.              server.aof_rewrite_perc &&  
  6.              server.aof_current_size > server.aof_rewrite_min_size)  
  7.          {  
  8.             long long base = server.aof_rewrite_base_size ?  
  9.                             server.aof_rewrite_base_size : 1;  
  10.             long long growth = (server.aof_current_size*100/base) - 100;  
  11.             if (growth >= server.aof_rewrite_perc) {  
  12.                 redisLog(REDIS_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth);  
  13.                 rewriteAppendOnlyFileBackground();  
  14.             }  
  15.          }  

config set appendonly yes

當客戶端發送該指令時,config.c中的configSetCommand函數會作出響應,startAppendOnly函數會執行AOF rewrite
  1. if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {  
  2.     int enable = yesnotoi(o->ptr);  
  3.   
  4.     if (enable == -1) goto badfmt;  
  5.     if (enable == 0 && server.aof_state != REDIS_AOF_OFF) {//appendonly no 關閉AOF  
  6.         stopAppendOnly();  
  7.     } else if (enable && server.aof_state == REDIS_AOF_OFF) {//appendonly yes rewrite AOF  
  8.         if (startAppendOnly() == REDIS_ERR) {  
  9.             addReplyError(c,  
  10.                 "Unable to turn on AOF. Check server logs.");  
  11.             return;  
  12.         }  
  13.     }  
  14. }  
  1. int startAppendOnly(void) {  
  2.     server.aof_last_fsync = server.unixtime;  
  3.     server.aof_fd = open(server.aof_filename,O_WRONLY|O_APPEND|O_CREAT,0644);  
  4.     redisAssert(server.aof_state == REDIS_AOF_OFF);  
  5.     if (server.aof_fd == -1) {  
  6.         redisLog(REDIS_WARNING,"Redis needs to enable the AOF but can't open the append only file: %s",strerror(errno));  
  7.         return REDIS_ERR;  
  8.     }  
  9.     if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {//rewrite  
  10.         close(server.aof_fd);  
  11.         redisLog(REDIS_WARNING,"Redis needs to enable the AOF but can't trigger a background AOF rewrite operation. Check the above logs for more info about the error.");  
  12.         return REDIS_ERR;  
  13.     }  
  14.     /* We correctly switched on AOF, now wait for the rerwite to be complete 
  15.      * in order to append data on disk. */  
  16.     server.aof_state = REDIS_AOF_WAIT_REWRITE;  
  17.     return REDIS_OK;  
  18. }  

Redis AOF rewrite機制的實現

從上述分析能夠看出rewrite的實現所有依靠rewriteAppendOnlyFileBackground函數,下面分析該函數,經過下面的代碼能夠看出,Redis是fork出一個子進程來操做AOF rewrite,而後子進程調用rewriteAppendOnlyFile函數,將數據寫到一個臨時文件temp-rewriteaof-bg-%d.aof中。若是子進程完成會經過exit(0)函數通知父進程rewrite結束,在serverCron函數中使用wait3函數接收子進程退出狀態,而後執行後續的AOF rewrite的收尾工做,後面將會分析。
父進程的工做主要包括清楚server.aof_rewrite_scheduled標誌,記錄子進程IDserver.aof_child_pid = childpid,記錄rewrite的開始時間server.aof_rewrite_time_start = time(NULL)等。
  1. int rewriteAppendOnlyFileBackground(void) {  
  2.     pid_t childpid;  
  3.     long long start;  
  4.   
  5.     // 後臺重寫正在執行  
  6.     if (server.aof_child_pid != -1) return REDIS_ERR;  
  7.     start = ustime();  
  8.     if ((childpid = fork()) == 0) {  
  9.         char tmpfile[256];  
  10.   
  11.         /* Child */  
  12.         closeListeningSockets(0);//  
  13.         redisSetProcTitle("redis-aof-rewrite");  
  14.         snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());  
  15.         if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {  
  16.             size_t private_dirty = zmalloc_get_private_dirty();  
  17.   
  18.             if (private_dirty) {  
  19.                 redisLog(REDIS_NOTICE,  
  20.                     "AOF rewrite: %zu MB of memory used by copy-on-write",  
  21.                     private_dirty/(1024*1024));  
  22.             }  
  23.             exitFromChild(0);  
  24.         } else {  
  25.             exitFromChild(1);  
  26.         }  
  27.     } else {  
  28.         /* Parent */  
  29.         server.stat_fork_time = ustime()-start;  
  30.         if (childpid == -1) {  
  31.             redisLog(REDIS_WARNING,  
  32.                 "Can't rewrite append only file in background: fork: %s",  
  33.                 strerror(errno));  
  34.             return REDIS_ERR;  
  35.         }  
  36.         redisLog(REDIS_NOTICE,  
  37.             "Background append only file rewriting started by pid %d",childpid);  
  38.         server.aof_rewrite_scheduled = 0;  
  39.         server.aof_rewrite_time_start = time(NULL);  
  40.         server.aof_child_pid = childpid;  
  41.         updateDictResizePolicy();  
  42.         /* We set appendseldb to -1 in order to force the next call to the 
  43.          * feedAppendOnlyFile() to issue a SELECT command, so the differences 
  44.          * accumulated by the parent into server.aof_rewrite_buf will start 
  45.          * with a SELECT statement and it will be safe to merge. */  
  46.         server.aof_selected_db = -1;  
  47.         replicationScriptCacheFlush();  
  48.         return REDIS_OK;  
  49.     }  
  50.     return REDIS_OK; /* unreached */  
  51. }  
接下來介紹rewriteAppendOnlyFile函數,該函數的主要工做爲:遍歷全部數據庫中的數據,將其寫入到臨時文件temp-rewriteaof-%d.aof中,寫入函數定義在rio.c中,比較簡單,而後將數據刷新到硬盤中,而後將文件名rename爲其調用者給定的臨時文件名,注意仔細看代碼,這裏並無修改成正式的AOF文件名。
在寫入文件時若是設置server.aof_rewrite_incremental_fsync參數,那麼在rioWrite函數中fwrite部分數據就會將數據fsync到硬盤中,來保證數據的正確性。
  1. int rewriteAppendOnlyFile(char *filename) {  
  2.     dictIterator *di = NULL;  
  3.     dictEntry *de;  
  4.     rio aof;  
  5.     FILE *fp;  
  6.     char tmpfile[256];  
  7.     int j;  
  8.     long long now = mstime();  
  9.   
  10.     /* Note that we have to use a different temp name here compared to the 
  11.      * one used by rewriteAppendOnlyFileBackground() function. */  
  12.     snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());  
  13.     fp = fopen(tmpfile,"w");  
  14.     if (!fp) {  
  15.         redisLog(REDIS_WARNING, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno));  
  16.         return REDIS_ERR;  
  17.     }  
  18.   
  19.     rioInitWithFile(&aof,fp); //初始化讀寫函數,rio.c  
  20.     //設置r->io.file.autosync = bytes;每32M刷新一次  
  21.     if (server.aof_rewrite_incremental_fsync)  
  22.         rioSetAutoSync(&aof,REDIS_AOF_AUTOSYNC_BYTES);  
  23.     for (j = 0; j < server.dbnum; j++) {//遍歷每一個數據庫  
  24.         char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";  
  25.         redisDb *db = server.db+j;  
  26.         dict *d = db->dict;  
  27.         if (dictSize(d) == 0) continue;  
  28.         di = dictGetSafeIterator(d);  
  29.         if (!di) {  
  30.             fclose(fp);  
  31.             return REDIS_ERR;  
  32.         }  
  33.   
  34.         /* SELECT the new DB */  
  35.         if (rioWrite(&aof,selectcmd,sizeof(selectcmd)-1) == 0) goto werr;  
  36.         if (rioWriteBulkLongLong(&aof,j) == 0) goto werr;  
  37.   
  38.         /* Iterate this DB writing every entry */  
  39.         while((de = dictNext(di)) != NULL) {  
  40.             sds keystr;  
  41.             robj key, *o;  
  42.             long long expiretime;  
  43.   
  44.             keystr = dictGetKey(de);  
  45.             o = dictGetVal(de);  
  46.             initStaticStringObject(key,keystr);  
  47.   
  48.             expiretime = getExpire(db,&key);  
  49.   
  50.             /* If this key is already expired skip it */  
  51.             if (expiretime != -1 && expiretime < now) continue;  
  52.   
  53.             /* Save the key and associated value */  
  54.             if (o->type == REDIS_STRING) {  
  55.                 /* Emit a SET command */  
  56.                 char cmd[]="*3\r\n$3\r\nSET\r\n";  
  57.                 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;  
  58.                 /* Key and value */  
  59.                 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;  
  60.                 if (rioWriteBulkObject(&aof,o) == 0) goto werr;  
  61.             } else if (o->type == REDIS_LIST) {  
  62.                 if (rewriteListObject(&aof,&key,o) == 0) goto werr;  
  63.             } else if (o->type == REDIS_SET) {  
  64.                 if (rewriteSetObject(&aof,&key,o) == 0) goto werr;  
  65.             } else if (o->type == REDIS_ZSET) {  
  66.                 if (rewriteSortedSetObject(&aof,&key,o) == 0) goto werr;  
  67.             } else if (o->type == REDIS_HASH) {  
  68.                 if (rewriteHashObject(&aof,&key,o) == 0) goto werr;  
  69.             } else {  
  70.                 redisPanic("Unknown object type");  
  71.             }  
  72.             /* Save the expire time */  
  73.             if (expiretime != -1) {  
  74.                 char cmd[]="*3\r\n$9\r\nPEXPIREAT\r\n";  
  75.                 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;  
  76.                 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;  
  77.                 if (rioWriteBulkLongLong(&aof,expiretime) == 0) goto werr;  
  78.             }  
  79.         }  
  80.         dictReleaseIterator(di);  
  81.     }  
  82.   
  83.     /* Make sure data will not remain on the OS's output buffers */  
  84.     fflush(fp);  
  85.     aof_fsync(fileno(fp));//將tempfile文件刷新到硬盤  
  86.     fclose(fp);  
  87.   
  88.     /* Use RENAME to make sure the DB file is changed atomically only 
  89.      * if the generate DB file is ok. */  
  90.     if (rename(tmpfile,filename) == -1) {//重命名文件名,注意rename後的文件也是一個臨時文件  
  91.         redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));  
  92.         unlink(tmpfile);  
  93.         return REDIS_ERR;  
  94.     }  
  95.     redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");  
  96.     return REDIS_OK;  
  97.   
  98. werr:  
  99.     fclose(fp);  
  100.     unlink(tmpfile);  
  101.     redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));  
  102.     if (di) dictReleaseIterator(di);  
  103.     return REDIS_ERR;  
  104. }  
AOF rewrite工做到這裏已經結束一半,上一篇文章提到若是server.aof_state != REDIS_AOF_OFF,那麼就會將客戶端請求指令修改的數據經過feedAppendOnlyFile函數追加到AOF文件中,那麼此時AOF已經rewrite了,必需要處理此時出現的差別數據,記得在feedAppendOnlyFile函數中有這麼一段代碼
  1. if (server.aof_child_pid != -1)  
  2.         aofRewriteBufferAppend((unsigned char*)buf,sdslen(buf));  
若是AOF rewrite正在進行,那麼就將修改數據的指令字符串存儲到server.aof_rewrite_buf_blocks鏈表中,等待AOF rewrite子進程結束後處理,處理此部分數據的代碼在serverCron函數中。須要指出的是wait3函數我不瞭解,可能下面註釋會有點問題。
  1. /* Check if a background saving or AOF rewrite in progress terminated. */  
  2. //若是RDB bgsave或AOF rewrite子進程已經執行,經過獲取子進程的退出狀態,對後續的工做進行處理  
  3. if (server.rdb_child_pid != -1 || server.aof_child_pid != -1) {//  
  4.     int statloc;  
  5.     pid_t pid;  
  6.   
  7.     if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {  
  8.         int exitcode = WEXITSTATUS(statloc);//獲取退出的狀態  
  9.         int bysignal = 0;  
  10.   
  11.         if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc);  
  12.   
  13.         if (pid == server.rdb_child_pid) {  
  14.             backgroundSaveDoneHandler(exitcode,bysignal);  
  15.         } else if (pid == server.aof_child_pid) {  
  16.             backgroundRewriteDoneHandler(exitcode,bysignal);  
  17.         } else {  
  18.             redisLog(REDIS_WARNING,  
  19.                 "Warning, detected child with unmatched pid: %ld",  
  20.                 (long)pid);  
  21.         }  
  22.         // 若是 BGSAVE 和 BGREWRITEAOF 都已經完成,那麼從新開始 REHASH  
  23.         updateDictResizePolicy();  
  24.     }  
  25. }  
對於AOF rewrite期間出現的差別數據,Server經過backgroundSaveDoneHandler函數將 server.aof_rewrite_buf_blocks鏈表中數據追加到新的AOF文件中。
backgroundSaveDoneHandler函數執行步驟:
一、經過判斷子進程的退出狀態,正確的退出狀態爲exit(0),即exitcode爲0,bysignal我不清楚具體意義,若是退出狀態正確,backgroundSaveDoneHandler函數纔會開始處理
二、經過對rewriteAppendOnlyFileBackground函數的分析,能夠知道rewrite後的AOF臨時文件名爲temp-rewriteaof-bg-%d.aof(%d=server.aof_child_pid)中,接着須要打開此臨時文件
三、調用aofRewriteBufferWrite函數將server.aof_rewrite_buf_blocks中差別數據寫到該臨時文件中
四、若是舊的AOF文件未打開,那麼打開舊的AOF文件,將文件描述符賦值給臨時變量oldfd
五、將臨時的AOF文件名rename爲正常的AOF文件名
六、若是舊的AOF文件未打開,那麼此時只須要關閉新的AOF文件,此時的server.aof_rewrite_buf_blocks數據應該爲空;若是舊的AOF是打開的,那麼將server.aof_fd指向newfd,而後根據相應的fsync策略將數據刷新到硬盤上
七、調用aofUpdateCurrentSize函數統計AOF文件的大小,更新server.aof_rewrite_base_size,爲serverCron中自動AOF rewrite作相應判斷
八、若是以前是REDIS_AOF_WAIT_REWRITE狀態,則設置server.aof_state爲REDIS_AOF_ON,由於只有「config set appendonly yes」指令纔會設置這個狀態,也就是須要寫完快照後,當即打開AOF;而BGREWRITEAOF不須要打開AOF
九、調用後臺線程去關閉舊的AOF文件
下面是backgroundSaveDoneHandler函數的註釋代碼

  1. /* A background append only file rewriting (BGREWRITEAOF) terminated its work. 
  2.  * Handle this. */  
  3. void backgroundRewriteDoneHandler(int exitcode, int bysignal) {  
  4.     if (!bysignal && exitcode == 0) {//子進程退出狀態正確  
  5.         int newfd, oldfd;  
  6.         char tmpfile[256];  
  7.         long long now = ustime();  
  8.   
  9.         redisLog(REDIS_NOTICE,  
  10.             "Background AOF rewrite terminated with success");  
  11.   
  12.         /* Flush the differences accumulated by the parent to the 
  13.          * rewritten AOF. */  
  14.         snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof",  
  15.             (int)server.aof_child_pid);  
  16.         newfd = open(tmpfile,O_WRONLY|O_APPEND);  
  17.         if (newfd == -1) {  
  18.             redisLog(REDIS_WARNING,  
  19.                 "Unable to open the temporary AOF produced by the child: %s", strerror(errno));  
  20.             goto cleanup;  
  21.         }  
  22.         //處理server.aof_rewrite_buf_blocks中DIFF數據  
  23.         if (aofRewriteBufferWrite(newfd) == -1) {  
  24.             redisLog(REDIS_WARNING,  
  25.                 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno));  
  26.             close(newfd);  
  27.             goto cleanup;  
  28.         }  
  29.   
  30.         redisLog(REDIS_NOTICE,  
  31.             "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", aofRewriteBufferSize());  
  32.   
  33.         /* The only remaining thing to do is to rename the temporary file to 
  34.          * the configured file and switch the file descriptor used to do AOF 
  35.          * writes. We don't want close(2) or rename(2) calls to block the 
  36.          * server on old file deletion. 
  37.          * 
  38.          * There are two possible scenarios: 
  39.          * 
  40.          * 1) AOF is DISABLED and this was a one time rewrite. The temporary 
  41.          * file will be renamed to the configured file. When this file already 
  42.          * exists, it will be unlinked, which may block the server. 
  43.          * 
  44.          * 2) AOF is ENABLED and the rewritten AOF will immediately start 
  45.          * receiving writes. After the temporary file is renamed to the 
  46.          * configured file, the original AOF file descriptor will be closed. 
  47.          * Since this will be the last reference to that file, closing it 
  48.          * causes the underlying file to be unlinked, which may block the 
  49.          * server. 
  50.          * 
  51.          * To mitigate the blocking effect of the unlink operation (either 
  52.          * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we 
  53.          * use a background thread to take care of this. First, we 
  54.          * make scenario 1 identical to scenario 2 by opening the target file 
  55.          * when it exists. The unlink operation after the rename(2) will then 
  56.          * be executed upon calling close(2) for its descriptor. Everything to 
  57.          * guarantee atomicity for this switch has already happened by then, so 
  58.          * we don't care what the outcome or duration of that close operation 
  59.          * is, as long as the file descriptor is released again. */  
  60.         if (server.aof_fd == -1) {  
  61.             /* AOF disabled */  
  62.   
  63.              /* Don't care if this fails: oldfd will be -1 and we handle that. 
  64.               * One notable case of -1 return is if the old file does 
  65.               * not exist. */  
  66.              oldfd = open(server.aof_filename,O_RDONLY|O_NONBLOCK);  
  67.         } else {  
  68.             /* AOF enabled */  
  69.             oldfd = -1; /* We'll set this to the current AOF filedes later. */  
  70.         }  
  71.   
  72.         /* Rename the temporary file. This will not unlink the target file if 
  73.          * it exists, because we reference it with "oldfd". */  
  74.         //把臨時文件更名爲正常的AOF文件名。因爲當前oldfd已經指向這個以前的正常文件名的文件,  
  75.         //因此當前不會形成unlink操做,得等那個oldfd被close的時候,內核判斷該文件沒有指向了,就刪除之。  
  76.         if (rename(tmpfile,server.aof_filename) == -1) {  
  77.             redisLog(REDIS_WARNING,  
  78.                 "Error trying to rename the temporary AOF file: %s", strerror(errno));  
  79.             close(newfd);  
  80.             if (oldfd != -1) close(oldfd);  
  81.             goto cleanup;  
  82.         }  
  83.         //若是AOF關閉了,那隻要處理新文件,直接關閉這個新的文件便可  
  84.         //可是這裏會不會致使服務器卡呢?這個newfd應該是臨時文件的最後一個fd了,不會的,  
  85.         //由於這個文件在本函數不會寫入數據,由於stopAppendOnly函數會清空aof_rewrite_buf_blocks列表。  
  86.         if (server.aof_fd == -1) {  
  87.             /* AOF disabled, we don't need to set the AOF file descriptor 
  88.              * to this new file, so we can close it. */  
  89.             close(newfd);  
  90.         } else {  
  91.             /* AOF enabled, replace the old fd with the new one. */  
  92.             oldfd = server.aof_fd;  
  93.             //指向新的fd,此時這個fd因爲上面的rename語句存在,已經爲正常aof文件名  
  94.             server.aof_fd = newfd;  
  95.             //fsync到硬盤  
  96.             if (server.aof_fsync == AOF_FSYNC_ALWAYS)  
  97.                 aof_fsync(newfd);  
  98.             else if (server.aof_fsync == AOF_FSYNC_EVERYSEC)  
  99.                 aof_background_fsync(newfd);  
  100.             server.aof_selected_db = -1; /* Make sure SELECT is re-issued */  
  101.             aofUpdateCurrentSize();  
  102.             server.aof_rewrite_base_size = server.aof_current_size;  
  103.   
  104.             /* Clear regular AOF buffer since its contents was just written to 
  105.              * the new AOF from the background rewrite buffer. */  
  106.             //rewrite獲得的確定是最新的數據,因此aof_buf中的數據沒有意義,直接清空  
  107.             sdsfree(server.aof_buf);  
  108.             server.aof_buf = sdsempty();  
  109.         }  
  110.   
  111.         server.aof_lastbgrewrite_status = REDIS_OK;  
  112.   
  113.         redisLog(REDIS_NOTICE, "Background AOF rewrite finished successfully");  
  114.         /* Change state from WAIT_REWRITE to ON if needed */  
  115.         //下面判斷是否須要打開AOF,好比bgrewriteaofCommand就不須要打開AOF。  
  116.         if (server.aof_state == REDIS_AOF_WAIT_REWRITE)  
  117.             server.aof_state = REDIS_AOF_ON;  
  118.   
  119.         /* Asynchronously close the overwritten AOF. */  
  120.         //讓後臺線程去關閉這個舊的AOF文件FD,只要CLOSE就行,會自動unlink的,由於上面已經有rename  
  121.         if (oldfd != -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE,(void*)(long)oldfd,NULL,NULL);  
  122.   
  123.         redisLog(REDIS_VERBOSE,  
  124.             "Background AOF rewrite signal handler took %lldus", ustime()-now);  
  125.     } else if (!bysignal && exitcode != 0) {  
  126.         server.aof_lastbgrewrite_status = REDIS_ERR;  
  127.   
  128.         redisLog(REDIS_WARNING,  
  129.             "Background AOF rewrite terminated with error");  
  130.     } else {  
  131.         server.aof_lastbgrewrite_status = REDIS_ERR;  
  132.   
  133.         redisLog(REDIS_WARNING,  
  134.             "Background AOF rewrite terminated by signal %d", bysignal);  
  135.     }  
  136.   
  137. cleanup:  
  138.     aofRewriteBufferReset();  
  139.     aofRemoveTempFile(server.aof_child_pid);  
  140.     server.aof_child_pid = -1;  
  141.     server.aof_rewrite_time_last = time(NULL)-server.aof_rewrite_time_start;  
  142.     server.aof_rewrite_time_start = -1;  
  143.     /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */  
  144.     if (server.aof_state == REDIS_AOF_WAIT_REWRITE)  
  145.         server.aof_rewrite_scheduled = 1;  
  146. }  

至此,AOF數據持久化已經所有結束了,剩下的就是一些細節的處理,以及一些Linux庫函數的理解,對於rename、unlink、wait3等庫 函數的深刻認識就去問Google吧。

小結


Redis AOF數據持久化的實現機制經過三篇文章基本上比較詳細的分析了, 但這只是從代碼層面去看AOF,對於AOF持久化的優缺點網上有不少分析,Redis的官方網站也有英文介紹,Redis的數據持久化還有一種方法叫RDB,更多RDB的內容等下次再分析。
感謝此篇博客給我在理解Redis AOF數據持久化方面的巨大幫助, http://chenzhenianqing.cn/articles/786.html,此篇博客對AOF的分析十分的詳細。
相關文章
相關標籤/搜索