Can we set C int array as a key's value in Redis by hiredis?

回眸只為那壹抹淺笑 提交于 2019-12-21 20:56:04

问题


given : int x[3] = {11,22,33}; how can save it as a key's value as binary data and get it

the hiredis give example to how to set binary 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);

but how about other data and how to get ?


回答1:


Storing directly binary data in a remote store without any kind of marshalling is a recipe for disaster. I would not recommend to do it: there are plenty of serialization protocols you could use to make binary data independent from the platform.

That said, to answer your question:

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

Note that this kind of code only works if you are sure that all your Redis clients run on systems with the same endianness and same sizeof(int).



来源:https://stackoverflow.com/questions/26799074/can-we-set-c-int-array-as-a-keys-value-in-redis-by-hiredis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!