使用hiredis将带有空格的多字符串用于redis

时间:2013-11-19 09:25:21

标签: c redis hiredis

我正在尝试将多字符串字符串转换为redis密钥 但是每个词都被添加为一个新元素 我怎么能避免这个

  #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis.h>

int main(int argc, char **argv) {
    redisContext *c;
    redisReply *reply;
    int j;
    struct timeval timeout = { 1, 500000 }; // 1.5 seconds                                                                                     
    c = redisConnectWithTimeout("192.168.77.101",6379, timeout);
    reply = redisCommand(c,"DEL mylist");
    freeReplyObject(reply);
    reply = redisCommand(c,"RPUSH mylist element 0");        freeReplyObject(reply);
    reply = redisCommand(c,"RPUSH mylist element 1");        freeReplyObject(reply);
    reply = redisCommand(c,"RPUSH mylist element 2");        freeReplyObject(reply);

    reply = redisCommand(c,"LRANGE mylist 0 -1");
    if (reply->type == REDIS_REPLY_ARRAY) {
        for (j = 0; j < reply->elements; j++) {
            printf("%u) %s\n", j, reply->element[j]->str);
        }
    }
    freeReplyObject(reply);
    redisFree(c);
    return 0;
}

我希望响应为3个值,但我得到6个值

1 个答案:

答案 0 :(得分:2)

嗯,这是预期的行为。您应该使用参数占位符来构建命令。请查看documentation

从hiredis源代码中提取:

/* Format a command according to the Redis protocol. This function
 * takes a format similar to printf:
 *
 * %s represents a C null terminated string you want to interpolate
 * %b represents a binary safe string
 *
 * When using %b you need to provide both the pointer to the string
 * and the length in bytes. Examples:
 *
 * len = redisFormatCommand(target, "GET %s", mykey);
 * len = redisFormatCommand(target, "SET %s %b", mykey, myval, myvallen);
 */

如果您按如下方式更改代码,则可以解决问题。

reply = redisCommand(c,"RPUSH mylist %s","element 0"); freeReplyObject(reply);
reply = redisCommand(c,"RPUSH mylist %s","element 1"); freeReplyObject(reply);
reply = redisCommand(c,"RPUSH mylist %s","element 2"); freeReplyObject(reply);

另外,我建议系统地测试hiredis API的返回码。它可能很麻烦,但它会在项目的后期阶段为您节省很多问题。