我们可以通过hiredis将C int数组设置为Redis中的键值吗? [英] Can we set C int array as a key's value in Redis by hiredis?

查看:70
本文介绍了我们可以通过hiredis将C int数组设置为Redis中的键值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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 ?

推荐答案

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

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

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

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).

这篇关于我们可以通过hiredis将C int数组设置为Redis中的键值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆