redis 返回值類型 和 rername-command相關內容

在redis源碼目錄redis-3.2.2\deps\hiredis\hiredis.h 裏面定義了redis命令的返回值類型

#define REDIS_REPLY_STRING 1
#define REDIS_REPLY_ARRAY 2
#define REDIS_REPLY_INTEGER 3
#define REDIS_REPLY_NIL 4
#define REDIS_REPLY_STATUS 5
#define REDIS_REPLY_ERROR 6 

redis-cli 代碼裏面輸出返回值的幾個函數分別是

static sds cliFormatReplyTTY(redisReply *r, char *prefix);

static sds cliFormatReplyRaw(redisReply *r)

static sds cliFormatReplyCSV(redisReply *r)

三個靜態函數 

比較常見的返回值類型是string類型 int類型 

還有一種類型 list類型的 函數裏面用了遞歸查找的方法

 case REDIS_REPLY_ARRAY:
        if (r->elements == 0) {
            out = sdscat(out,"(empty list or set)\n");
        } else {
            unsigned int i, idxlen = 0;
            char _prefixlen[16];
            char _prefixfmt[16];
            sds _prefix;
            sds tmp;


            /* Calculate chars needed to represent the largest index */
            i = r->elements;
            do {
                idxlen++;
                i /= 10;
            } while(i);


            /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
            memset(_prefixlen,' ',idxlen+2);
            _prefixlen[idxlen+2] = '\0';
            _prefix = sdscat(sdsnew(prefix),_prefixlen);


            /* Setup prefix format for every entry */
            snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%ud) ",idxlen);


            for (i = 0; i < r->elements; i++) {
                /* Don't use the prefix for the first element, as the parent
                 * caller already prepended the index number. */
                out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);


                /* Format the multi bulk entry */
                tmp = cliFormatReplyTTY(r->element[i],_prefix);
                out = sdscatlen(out,tmp,sdslen(tmp));
                sdsfree(tmp);
            }
            sdsfree(_prefix);
        }
    break;

考慮到命令可能有多組數據  一層一層的去獲取數據

涉及到一些問題

比如 我們調用一個C的接口執行redis命令 打印調試信息一定要知道這個redisReply  這個結構體的意思 否則會引起內存錯誤

        reply=redisCommand(c,command); 

  printf("%s\n",reply->str);

        如果reply->str是個空指針會內存錯誤

舉個例子 command如果是 config get maxmemory 的時候 返回的是個數據集 這樣去打印reply->str的時候就會報內存錯誤了 

數據集的值是保存

   

	/* This is the reply object returned by redisCommand() */
typedef struct redisReply {
    int type; /* REDIS_REPLY_* */
    long long integer; /* The integer when type is REDIS_REPLY_INTEGER */
    int len; /* Length of string */
    char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */
    size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */
    struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */
} redisReply;

這裏面的 element這個二級指針裏面

我們如果取數據 需要printf("%s\n",reply->elment[i]->str); 這樣才能取出數據

二、rename 相關

redis提供對命令重命令的功能

rename-command SET b840fc02d524045429941cc15f59e41cb7be6c51

這是官方提供的例子

rename把命令替換成一個字符串  (特別注意字符串必須用字母開頭 不能使用數字)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章