我们可以通过hiredis将C int数组设置为Redis中的键值吗?

时间:2014-11-07 10:25:57

标签: c redis hiredis

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

hiredis给出了如何设置二进制safestring

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

但其他数据怎么样?如何获得?

1 个答案:

答案 0 :(得分: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)的系统上运行时,此类代码才有效。