Redis源碼分析(二)redis-cli.c

文章目錄

    • 1. int main()
    • 2. parseOptions(int argc, char **argv) 進行ip和port的改變
    • 3. lookupCommand(char *name) 查找命令,判斷命令合法
    • 3.2 strcasecmp(name,cmdTable[j].name)
    • 3.1 redisCommand cmdTable[]
    • 4. cliSendCommand(int argc, char **argv)
    • 4.1 cliConnect(void)
    • 8.1 9.1 cliReadLine(int fd)
    • 8 cliReadSingleLineReply(int fd)
    • 9 cliReadBulkReply(int fd)
    • cliReadMultiBulkReply(int fd)
    • cliReadReply(int fd)
    • readArgFromStdin(void)

1. int main()

int main(int argc, char **argv) {int firstarg, j;char **argvcopy;struct redisCommand *rc;config.hostip = "127.0.0.1";config.hostport = 6379;firstarg = parseOptions(argc,argv);argc -= firstarg;argv += firstarg;/* Turn the plain C strings into Sds strings */argvcopy = zmalloc(sizeof(char*)*argc+1);for(j = 0; j < argc; j++)argvcopy[j] = sdsnew(argv[j]);if (argc < 1) {fprintf(stderr, "usage: redis-cli [-h host] [-p port] cmd arg1 arg2 arg3 ... argN\n");fprintf(stderr, "usage: echo \"argN\" | redis-cli [-h host] [-p port] cmd arg1 arg2 ... arg(N-1)\n");fprintf(stderr, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");fprintf(stderr, "example: cat /etc/passwd | redis-cli set my_passwd\n");fprintf(stderr, "example: redis-cli get my_passwd\n");exit(1);}/* Read the last argument from stdandard input if needed */if ((rc = lookupCommand(argv[0])) != NULL) {if (rc->arity > 0 && argc == rc->arity-1) {sds lastarg = readArgFromStdin();argvcopy[argc] = lastarg;argc++;}}return cliSendCommand(argc, argvcopy);
}

2. parseOptions(int argc, char **argv) 進行ip和port的改變

static int parseOptions(int argc, char **argv) {int i;for (i = 1; i < argc; i++) {int lastarg = i==argc-1;if (!strcmp(argv[i],"-h") && !lastarg) {char *ip = zmalloc(32);if (anetResolve(NULL,argv[i+1],ip) == ANET_ERR) {printf("Can't resolve %s\n", argv[i]);exit(1);}config.hostip = ip;i++;} else if (!strcmp(argv[i],"-p") && !lastarg) {config.hostport = atoi(argv[i+1]);i++;} else {break;}}return i;
}

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>#include "anet.h"
#include "sds.h"
#include "adlist.h"
#include "zmalloc.h"#define REDIS_CMD_INLINE 1
#define REDIS_CMD_BULK 2#define REDIS_NOTUSED(V) ((void) V)static struct config {char *hostip;int hostport;
} config;struct redisCommand {char *name;int arity;int flags;
};

3. lookupCommand(char *name) 查找命令,判斷命令合法

static struct redisCommand *lookupCommand(char *name) {int j = 0;while(cmdTable[j].name != NULL) {if (!strcasecmp(name,cmdTable[j].name)) return &cmdTable[j];j++;}return NULL;
}

3.2 strcasecmp(name,cmdTable[j].name)

后面的版本把這個比較進行了處理,如SeT,GET等

3.1 redisCommand cmdTable[]

static struct redisCommand cmdTable[] = {{"get",2,REDIS_CMD_INLINE},{"set",3,REDIS_CMD_BULK},{"setnx",3,REDIS_CMD_BULK},{"del",-2,REDIS_CMD_INLINE},{"exists",2,REDIS_CMD_INLINE},{"incr",2,REDIS_CMD_INLINE},{"decr",2,REDIS_CMD_INLINE},{"rpush",3,REDIS_CMD_BULK},{"lpush",3,REDIS_CMD_BULK},{"rpop",2,REDIS_CMD_INLINE},{"lpop",2,REDIS_CMD_INLINE},{"llen",2,REDIS_CMD_INLINE},{"lindex",3,REDIS_CMD_INLINE},{"lset",4,REDIS_CMD_BULK},{"lrange",4,REDIS_CMD_INLINE},{"ltrim",4,REDIS_CMD_INLINE},{"lrem",4,REDIS_CMD_BULK},{"sadd",3,REDIS_CMD_BULK},{"srem",3,REDIS_CMD_BULK},{"smove",4,REDIS_CMD_BULK},{"sismember",3,REDIS_CMD_BULK},{"scard",2,REDIS_CMD_INLINE},{"spop",2,REDIS_CMD_INLINE},{"sinter",-2,REDIS_CMD_INLINE},{"sinterstore",-3,REDIS_CMD_INLINE},{"sunion",-2,REDIS_CMD_INLINE},{"sunionstore",-3,REDIS_CMD_INLINE},{"sdiff",-2,REDIS_CMD_INLINE},{"sdiffstore",-3,REDIS_CMD_INLINE},{"smembers",2,REDIS_CMD_INLINE},{"incrby",3,REDIS_CMD_INLINE},{"decrby",3,REDIS_CMD_INLINE},{"getset",3,REDIS_CMD_BULK},{"randomkey",1,REDIS_CMD_INLINE},{"select",2,REDIS_CMD_INLINE},{"move",3,REDIS_CMD_INLINE},{"rename",3,REDIS_CMD_INLINE},{"renamenx",3,REDIS_CMD_INLINE},{"keys",2,REDIS_CMD_INLINE},{"dbsize",1,REDIS_CMD_INLINE},{"ping",1,REDIS_CMD_INLINE},{"echo",2,REDIS_CMD_BULK},{"save",1,REDIS_CMD_INLINE},{"bgsave",1,REDIS_CMD_INLINE},{"shutdown",1,REDIS_CMD_INLINE},{"lastsave",1,REDIS_CMD_INLINE},{"type",2,REDIS_CMD_INLINE},{"flushdb",1,REDIS_CMD_INLINE},{"flushall",1,REDIS_CMD_INLINE},{"sort",-2,REDIS_CMD_INLINE},{"info",1,REDIS_CMD_INLINE},{"mget",-2,REDIS_CMD_INLINE},{"expire",3,REDIS_CMD_INLINE},{"ttl",2,REDIS_CMD_INLINE},{"slaveof",3,REDIS_CMD_INLINE},{"debug",-2,REDIS_CMD_INLINE},{NULL,0,0}
};
static int cliReadReply(int fd);

4. cliSendCommand(int argc, char **argv)

static int cliSendCommand(int argc, char **argv) {struct redisCommand *rc = lookupCommand(argv[0]);int fd, j, retval = 0;sds cmd = sdsempty();if (!rc) {fprintf(stderr,"Unknown command '%s'\n",argv[0]);return 1;}if ((rc->arity > 0 && argc != rc->arity) ||(rc->arity < 0 && argc < -rc->arity)) {fprintf(stderr,"Wrong cliConnect of arguments for '%s'\n",rc->name);return 1;}if ((fd = cliConnect()) == -1) return 1;/* Build the command to send */for (j = 0; j < argc; j++) {if (j != 0) cmd = sdscat(cmd," ");if (j == argc-1 && rc->flags & REDIS_CMD_BULK) {cmd = sdscatprintf(cmd,"%d",sdslen(argv[j]));} else {cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));}}cmd = sdscat(cmd,"\r\n");if (rc->flags & REDIS_CMD_BULK) {cmd = sdscatlen(cmd,argv[argc-1],sdslen(argv[argc-1]));cmd = sdscat(cmd,"\r\n");}anetWrite(fd,cmd,sdslen(cmd));retval = cliReadReply(fd);if (retval) {close(fd);return retval;}close(fd);return 0;
}

4.1 cliConnect(void)

static int cliConnect(void) {char err[ANET_ERR_LEN];int fd;fd = anetTcpConnect(err,config.hostip,config.hostport);if (fd == ANET_ERR) {fprintf(stderr,"Connect: %s\n",err);return -1;}anetTcpNoDelay(NULL,fd);return fd;
}

8.1 9.1 cliReadLine(int fd)

static sds cliReadLine(int fd) {sds line = sdsempty();while(1) {char c;ssize_t ret;ret = read(fd,&c,1);if (ret == -1) {sdsfree(line);return NULL;} else if ((ret == 0) || (c == '\n')) {break;} else {line = sdscatlen(line,&c,1);}}return sdstrim(line,"\r\n");
}

8 cliReadSingleLineReply(int fd)

static int cliReadSingleLineReply(int fd) {sds reply = cliReadLine(fd);if (reply == NULL) return 1;printf("%s\n", reply);return 0;
}

9 cliReadBulkReply(int fd)

static int cliReadBulkReply(int fd) {sds replylen = cliReadLine(fd);char *reply, crlf[2];int bulklen;if (replylen == NULL) return 1;bulklen = atoi(replylen);if (bulklen == -1) {sdsfree(replylen);printf("(nil)");return 0;}reply = zmalloc(bulklen);anetRead(fd,reply,bulklen);anetRead(fd,crlf,2);if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {zfree(reply);return 1;}if (isatty(fileno(stdout)) && reply[bulklen-1] != '\n')printf("\n");zfree(reply);return 0;
}

cliReadMultiBulkReply(int fd)

static int cliReadMultiBulkReply(int fd) {sds replylen = cliReadLine(fd);int elements, c = 1;if (replylen == NULL) return 1;elements = atoi(replylen);if (elements == -1) {sdsfree(replylen);printf("(nil)\n");return 0;}if (elements == 0) {printf("(empty list or set)\n");}while(elements--) {printf("%d. ", c);if (cliReadReply(fd)) return 1;c++;}return 0;
}

cliReadReply(int fd)

static int cliReadReply(int fd) {char type;if (anetRead(fd,&type,1) <= 0) exit(1);switch(type) {case '-':printf("(error) ");cliReadSingleLineReply(fd);return 1;case '+':case ':':return cliReadSingleLineReply(fd);case '$':return cliReadBulkReply(fd);case '*':return cliReadMultiBulkReply(fd);default:printf("protocol error, got '%c' as reply type byte\n", type);return 1;}
}

readArgFromStdin(void)

static sds readArgFromStdin(void) {char buf[1024];sds arg = sdsempty();while(1) {int nread = read(fileno(stdin),buf,1024);if (nread == 0) break;else if (nread == -1) {perror("Reading from standard input");exit(1);}arg = sdscatlen(arg,buf,nread);}return arg;
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/382375.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/382375.shtml
英文地址,請注明出處:http://en.pswp.cn/news/382375.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C語言中有bool變量嗎?

1.C/C中定義的數據類型&#xff1a; C語言中定義了6種基本數據類型&#xff1a;short,int,long,float,double,char 4種構造類型&#xff1a;數組&#xff0c;結構體&#xff08;struct&#xff09;&#xff0c;共用類型(union)&#xff0c;枚舉類型(enum) 指針類型和空類型 C語…

redis源碼剖析(三)——基礎數據結構

文章目錄SDS鏈表字典這篇文章關于 Redis 的基礎數據:SDS SDS &#xff08;Simple Dynamic String&#xff09;是 Redis 最基礎的數據結構。直譯過來就是”簡單的動態字符串“。Redis 自己實現了一個動態的字符串&#xff0c;而不是直接使用了 C 語言中的字符串。 sds 的數據結…

C++迭代器使用錯誤總結

指針和迭代器的區別&#xff1a; 迭代器&#xff1a; &#xff08;1&#xff09;迭代器不是指針&#xff0c;是類模板&#xff0c;表現的像指針。他只是模擬了指針的一些功能&#xff0c;通過重載了指針的一些操作符&#xff0c;->,*, --等封裝了指針&#xff0c;是一…

redis源碼剖析(四)跳表

文章目錄整數集合跳躍表壓縮列表總結整數集合 當一個集合只包含整數&#xff0c;且這個集合的元素不多的時候&#xff0c;Redis 就會使用整數集合 intset 。首先看 intset 的數據結構&#xff1a; typedef struct intset {// 編碼方式uint32_t encoding;// 集合包含的元素數量…

vivo C/C++工程師 HR視頻面試問題總結20180807

一開始沒想到這次視頻面是HR面試&#xff0c;還以為是技術面試&#xff0c;畢竟上次面試的時候技術問題問的相對比較少&#xff0c;所以面試準備方向有點兒錯了&#xff0c;不過還是總結一下具體問題。 1&#xff09;自我介紹&#xff1a;吸取了上次自我介紹的經驗&#xff0c;…

在Redis客戶端設置連接密碼 并演示密碼登錄

我們先連接到Redis服務 然后 我們要輸入 CONFIG SET requirepass “新密碼” 例如 CONFIG SET requirepass "A15167"這樣 密碼就被設置成立 A15167 我們 輸入 AUTH 密碼 例如 AUTH A15167這里 返回OK說明成功了 然后 我們退出在登錄就真的需要 redis-cli -h IP地…

redis源碼剖析(五)—— 字符串,列表,哈希,集合,有序集合

文章目錄對象REDIS_STRING &#xff08;字符串&#xff09;REDIS_LIST 列表REDIS_SET &#xff08;集合&#xff09;REDIS_ZSET &#xff08;有序集合&#xff09;REDIS_HASH (hash表)int refcount&#xff08;引用計數器&#xff09;unsigned lru:REDIS_LRU_BITS對象 對于 Re…

函數sscanf小結

1.sscanf用于處理固定格式的字符串&#xff0c;包含在頭文件<cstdio>中&#xff0c;函數原型為&#xff1a; int sscanf(const char *buffer,const char*format,[]argument ]...); 其中:buffer代表著要存儲的數據&#xff0c;format 代表格式控制字符串&#xff0c;arg…

redis源碼剖析(六)—— Redis 數據庫、鍵過期的實現

文章目錄數據庫的實現數據庫讀寫操作鍵的過期實現數據庫的實現 我們先看代碼 server.h/redisServer struct redisServer{...//保存 db 的數組redisDb *db;//db 的數量int dbnum;... }再看redisDb的代碼&#xff1a; typedef struct redisDb {dict *dict; /*…

多益網絡 視頻面試面試總結20180816

1.首先是自我介紹&#xff1a;因為等了半個小時&#xff0c;所以有點兒緊張&#xff0c;只說了一下自己的學校&#xff0c;愛好和興趣&#xff1b; 2.介紹了一個自己的最成功的項目&#xff1a;我介紹了一個關于GPS導航的項目&#xff0c;介紹了項目的內容和項目的一些工作&am…

redis源碼剖析(七)—— Redis 數據結構dict.c

文章目錄dict.hdict.cdict.h //定義錯誤相關的碼 #define DICT_OK 0 #define DICT_ERR 1//實際存放數據的地方 typedef struct dictEntry {void *key;void *val;struct dictEntry *next; } dictEntry;//哈希表的定義 typedef struct dict {//指向實際的哈希表記錄(用數組開鏈的…

簡述linux中動態庫和靜態庫的制作調用流程

假設現在有這些文件&#xff1a;sub.c add.c div.c mul.c mainc head.h&#xff08;前4個.C文件的頭文件&#xff09; 1.靜態庫制作流程 gcc -c sub.c add.c div.c mul.c -->生成 .o目標文件文件 ar rcs libmycal.a *.o …

redis源碼剖析(八)—— 當你啟動Redis的時候,Redis做了什么

文章目錄啟動過程初始化server結構體main函數會調用initServer函數初始化服務器狀態載入持久化文件&#xff0c;還原數據庫開始監聽事件流程圖啟動過程 初始化server結構體從配置文件夾在加載參數初始化服務器載入持久化文件開始監聽事件 初始化server結構體 服務器的運行ID…

linux中錯誤總結歸納

1.使用gcc編譯C文件&#xff0c;C文件在for循環語句中出現變量定義 編譯器提示錯誤&#xff1a;“for”loop initial declarations are only allowed in C99 mode. note:use option -stdc99or-stdgnu99 to compile; 原因&#xff1a;gcc的標準是基于c89的&#xff0c;c89不能在…

redis源碼剖析(十一)—— Redis字符串相關函數實現

文章目錄初始化字符串字符串基本操作字符串拼接操作other獲取指定范圍里的字符串將字符串中的所有字符均轉為小寫的形式將字符串中所有字符均轉為大寫的形式字符串比較other#define SDS_ABORT_ON_OOM#include "sds.h" #include <stdio.h> #include <stdlib.…

makefile內容小結

makefile中每個功能主要分為三部分&#xff1a;目標&#xff0c;依賴條件和命令語句 1.支持對比更新的Makefile寫法&#xff08;只會編譯文件時.o文件和.c文件時間不一致的文件&#xff09; 2.使用makefile自動變量和自定義變量的makefile寫法 其中&#xff1a;這三個符號為ma…

事務隔離級別動圖演示

事務的基本要素&#xff08;ACID&#xff09; 原子性&#xff08;Atomicity&#xff09; 事務開始后所有操作&#xff0c;要么全部做完&#xff0c;要么全部不做&#xff0c;不可能停滯在中間環節。事務執行過程中出錯&#xff0c;會回滾到事務開始前的狀態&#xff0c;所有的…

C/C++的優點和缺點

1.C/C語言的優點 C語言是面向過程的語言&#xff0c;常用來編寫操作系統。C語言是從C語言發展過來的&#xff0c;是一門面向對象的語言&#xff0c;它繼承了C語言的優勢&#xff0c;同時也添加了三個主要的內容&#xff1a;Oriented-Object class,Template,STL. 1)C/C可以潛入…

C/C++命令行參數那點事

int main(int argc, char *argv[ ]); 1.命令行參數&#xff1a;在命令行中給定的參數&#xff1b; 2.命令行參數在對函數main的調用時&#xff0c;主要有兩個參數送到main,一個是argc(argument count),命令行參數的個數&#xff0c;另外一個是argv,命令行參數的數組,命令行參…

mysql row_id為什么是6字節?為什么是8字節

mysql row_id是幾個字節&#xff1f; row_id InnoDB表中在沒有默認主鍵的情況下會生成一個6字節空間的自動增長主鍵 row_id是整型還是字符型&#xff1f; 源代碼中 row_id 是 ib_uint64_t 這是 8字節 uint64_t 是整形 為什么是6個字節&#xff1f; P.S. Base64編碼說明 B…