Domanda

Considera il seguente esempio:

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <hiredis/hiredis.h>

int main(int argc, char **argv) {
  redisContext *redis;
  redisReply *reply;

  redis = redisConnect("127.0.0.1", 6379);
  if(redis->err) {
    fprintf(stderr, "Connection error: %s\n", redis->errstr);
    exit(EXIT_FAILURE);
  }

  reply = redisCommand(redis, "SET %s %s", "foo", "bar");
  printf("SET %s %s: %s\n", "foo", "bar", reply->str);
  freeReplyObject(reply);

  reply = redisCommand(redis, "SET %s %s", "name", "value");
  printf("SET %s %s: %s\n", "name", "value", reply->str);
  freeReplyObject(reply);

  reply = redisCommand(redis, "MGET %s %s", "foo", "name");
  printf("MGET %s %s: %s\n", "foo", "name", reply->str);
  freeReplyObject(reply);

  exit(EXIT_SUCCESS);
}
.

L'output è:

PING: PONG
SET foo bar: OK
GET foo: bar
SET name value: OK
MGET foo name: (null)
.

Si tratta di ritorno da Mget.Posso ottenere le chiavi multi usando hiredis?

Lorem Ipsum Dolor Sit Amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.(È per il controllo stupido codice / controllo del testo.)

È stato utile?

Soluzione

Un Redisreply è un oggetto digitato (vedere il campo Tipo) e una risposta multi-bulk ha un tipo specifico (redis_reply_array).Il campo STR non è rilevante in tal caso.

Dalla documentazione Hiredis:

The number of elements in the multi bulk reply is stored in reply->elements.
Every element in the multi bulk reply is a redisReply object as well
and can be accessed via reply->element[..index..].
Redis may reply with nested arrays but this is fully supported.
.

Quindi il tuo codice dovrebbe essere cambiato come segue:

reply = redisCommand(redis, "MGET %s %s", "foo", "name" );
if ( reply->type == REDIS_REPLY_ERROR )
  printf( "Error: %s\n", reply->str );
else if ( reply->type != REDIS_REPLY_ARRAY )
  printf( "Unexpected type: %d\n", reply->type );
else 
{
  int i;
  for ( i=0; i<reply->elements; ++i )
    printf( "Result: %s\n", reply->element[i]->str );
}
freeReplyObject(reply);
.

Con questa modifica, l'uscita è ora:

SET foo bar: OK
SET name value: OK
Result: bar
Result: value
.

Nota: non è necessario liberare ogni singolo elemento da quando freereplyObject elimina l'intero albero.

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