1

我正在尝试将一个多字字符串推送到一个 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 个值

4

1 回答 1

3

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

从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 的返回码。这可能很麻烦,但它会在项目的后期为您节省很多问题。

于 2013-11-19T10:53:18.983 回答