c++redishiredis

[hiredis]Multiple hincrbys only return one result(REDIS_REPLY_INTEGER)


When using hiredis, use redisAppendCommand to put multiple hincrby commands, the reply->type result of redisGetReply is REDIS_REPLY_INTEGER, and only one of the results is returned.
But when I use hmget, the result of reply->type is REDIS_REPLY_ARRAY.


Solution

  • Since you call redisAppendCommand multiple times, you should call redisGetReply the same number of times to get all replies. For each reply, it's of type REDIS_REPLY_INTEGER. Because the reply type of hincrby is integer type, or array type.

    The reply type of hmget is array reply, and that's why you get REDIS_REPLY_ARRAY.

    Since you tag the question with c++, you can try redis-plus-plus, which is a user-friendly C++ client for Redis and you don't need to parse the reply manually:

    auto r = sw::redis::Redis("tcp://127.0.0.1:6379");
    for (auto idx = 0; idx < 5; ++idx) {
        r.hincrby("key", "field", 1);
    }
    std::vector<std::string> fields = {"f1", "f2"};
    std::vector<std::optinal<std::string>> vals;
    r.hmget("key", fields.begin(), fields.end(), std::back_inserter(vals));
    

    Disclaimer: I'm the author of redis-plus-plus.