【问题标题】:rpush multi-word string with spaces to redis using hiredis使用hiredis将带有空格的多词字符串rpush到redis
【发布时间】:2013-11-19 09:25:20
【问题描述】:

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

【问题讨论】:

    标签: c redis hiredis


    【解决方案1】:

    嗯,这是预期的行为。您应该使用参数占位符来构建您的命令。请查看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 的返回码。这可能很麻烦,但它会为您在项目的后期阶段省去很多问题。

    【讨论】:

    • reply = redisCommand(c,"RPUSH mylist %s","element 2");工作正常如何捕获此命令的错误回复-> str 始终设置为 null
    • github.com/redis/hiredis#using-replies - 至少检查reply 不是NULL,并且reply->type != REDIS_REPLY_ERROR - 如果出现错误,您可能在c->err 和c->errstr
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 2014-08-30
    • 2015-09-21
    • 2022-07-29
    • 1970-01-01
    • 2017-05-12
    相关资源
    最近更新 更多