2

给定: int x[3] = {11,22,33}; 如何将其保存为密钥的值作为二进制数据并获取它

hiredis 举例说明如何设置二进制安全字符串

   /* Set a key using binary safe API */
   reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
   printf("SET (binary API): %s\n", reply->str);
   freeReplyObject(reply);

但是其他数据如何以及如何获取?

4

1 回答 1

2

将二进制数据直接存储在远程存储中而不进行任何编组是灾难的根源。我不建议这样做:有很多序列化协议可以用来使二进制数据独立于平台。

也就是说,回答你的问题:

// This is the key
int k[3] = {11,22,33};

// This is the value
int v[4] = {0,1,2,3};
redisReply *reply = 0;

// Store the key/value: note the usage of sizeof to get the size of the arrays (in bytes)
reply = redisCommand(context, "SET %b %b", k, (size_t) sizeof(k), v, (size_t) sizeof(v) );
if (!reply)
    return REDIS_ERR;
freeReplyObject(reply);

// Now, get the value back, corresponding to the same key
reply = redisCommand(context, "GET %b", k, (size_t) sizeof(k) );
if ( !reply )
    return REDIS_ERR;
if ( reply->type != REDIS_REPLY_STRING ) {
    printf("ERROR: %s", reply->str);
} else {

    // Here, it is safer to make a copy to be sure memory is properly aligned
    int *val = (int *) malloc( reply->len );
    memcpy( val, reply->str, reply->len);
    for (int i=0; i<reply->len/sizeof(int); ++i )
        printf("%d\n",val[i]);
    free( val );
}
freeReplyObject(reply);

请注意,仅当您确定所有 Redis 客户端都在具有相同字节序和相同 sizeof(int) 的系统上运行时,这种代码才有效。

于 2014-11-07T16:31:28.927 回答