首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我们是否可以将Can数组设置为雇用人员在Redis中的键值?

我们是否可以将Can数组设置为雇用人员在Redis中的键值?
EN

Stack Overflow用户
提问于 2014-11-07 10:25:57
回答 1查看 3.1K关注 0票数 2

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

雇用人员举例说明如何设置二进制安全字符串。

代码语言:javascript
复制
   /* 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);

但是其他的数据和如何获取呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-07 16:31:28

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

尽管如此,要回答你的问题:

代码语言:javascript
复制
// 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客户端都运行在具有相同的endianness和相同大小(Int)的系统上时,此类代码才能工作。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26799074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档