Domanda

I am trying to rpush a multiword string to a redis key But everyword is getting added as a new element How can I avoid this

  #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;
}

I expect the response to be 3 values , but I get 6 values

È stato utile?

Soluzione

Well, this is the expected behavior. You are supposed to use parameter placeholders to build your commands. Please have a look at the documentation.

Extracted from hiredis source code:

/* 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);
 */

If you change your code as follows, it will fix the problem.

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);

Also, I would suggest to systematically test the return codes of hiredis APIs. It may be cumbersome, but it will save you a lot of problems in a later phase of your project.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top