Redis流行的原因( 四 )

判断是否开启了AOF

  • 是:则通过loadAppendOnlyFile() 加载AOF文件
  • 否:通过rdbLoad() 加载RDB文件
loadAppendOnlyFile()
/* Replay the append log file. On success C_OK is returned. On non fatal * error (the append only file is zero-length) C_ERR is returned. On * fatal error an error message is logged and the program exists. */int loadAppendOnlyFile(char *filename) {struct client *fakeClient;FILE *fp = fopen(filename,"r");....../* Check if this AOF file has an RDB preamble. In that case we need to* load the RDB file and later continue loading the AOF tail. */char sig[5]; /* "REDIS" */if (fread(sig,1,5,fp) != 5 || memcmp(sig,"REDIS",5) != 0) {/* No RDB preamble, seek back at 0 offset. */if (fseek(fp,0,SEEK_SET) == -1) goto readerr;} else {/* RDB preamble. Pass loading the RDB functions. */rio rdb;serverLog(LL_NOTICE,"Reading RDB preamble from AOF file...");if (fseek(fp,0,SEEK_SET) == -1) goto readerr;rioInitWithFile(if (rdbLoadRio(goto readerr;} else {serverLog(LL_NOTICE,"Reading the remaining AOF tail...");}}/* Read the actual AOF file, in REPL format, command by command. */while(1) {int argc, j;unsigned long len;robj **argv;char buf[128];sds argsds;struct redisCommand *cmd;/* Serve the clients from time to time */if (!(loops++ % 1000)) {loadingProgress(ftello(fp));processEventsWhileBlocked();}if (fgets(buf,sizeof(buf),fp) == NULL) {if (feof(fp))break;elsegoto readerr;}......}......}通过读取AOF文件的前5个字符来判断是否是RDB+AOF混合模式
  • 是:则先加载RDB数据(二进制数据) , 再一条一条的加载AOF数据(RESP协议格式数据)
  • 否:一条一条的加载AOF数据(RESP协议格式数据)
大致的重启数据加载流程为:
Redis流行的原因文章插图
小结至于Redis为什么是最流行的键值对存储数据库 , 仁者见仁智者见智 。
个人认为 , 总结几点:
  1. 是开源的(节约企业自研成本)
  2. 数据类型丰富(不仅仅是单纯的k-v)
  3. 处理速度快(单机读写10W+左右)
  4. 支持数据持久化
  5. 多种语言API支持
附:曾有一同事在追溯Redis源码之后 , 评价道“这是我看过最舒服的源码” 。 源码注释详细不说 , 各种变量、函数名称也是十分标准 。 由此可见一斑