redis:我可以在redis中存储一个包含指向数组指针的c/c++结构类型吗?

neekobn8  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(383)

我有这样一个结构:

struct father {
    int child_n; //the number of children
    int *child_age; //childrens' age
}

我可以在redis中存储这种具有可变长度数组的结构吗?

cqoc49vn

cqoc49vn1#

我用嵌套的*redis list解决了这个问题,下面是一个例子:


# include <iostream>

# include <string>

# include <cstring>

# include <hiredis/hiredis.h>

typedef struct stu {
    int stu_num;
    int* stu_age;
} stu;

using namespace std;

void put_stus(string key, stu students) {
    // connect to Redis server
    redisContext *connect = redisConnect("127.0.0.1",6379);
    if(!connect) {
        cout << "connect to redis fail" << endl;
        exit(-1);
    }

    // upload students' age
    redisReply *r;
    for(int i = 0;i < students.stu_num;i++) {
        r = (redisReply *)redisCommand(connect, "RPUSH %s:age %b",key,&students.stu_age[i],sizeof(students.stu_age[i]));
        if(r->type == REDIS_REPLY_ERROR) {
            cout << "put_stus error" << endl;
            exit(-1);
        }
        freeReplyObject(r);
    }
    // upload struct
    r = (redisReply *)redisCommand(connect, "SET %s %b",key,&students,sizeof(students));
    if(r->type == REDIS_REPLY_ERROR) {
        cout << "put_stus error" <<endl;
        exit(-1);
    }
    freeReplyObject(r);
    redisFree(connect);
}

void get_stus(string key, stu *r_students) {
    // connect to Redis Server
    redisContext *connect = redisConnect("127.0.0.1",6379);
    if(!connect) {
        cout << "connect to redis fail" << endl;
        exit(-1);
    }

    // Get sturct
    redisReply *r;
    r = (redisReply *)redisCommand(connect, "GET %s",key);
    if(r->type == REDIS_REPLY_ERROR) {
        cout << "get_stus error" <<endl;
        exit(-1);
    }
    memcpy(r_students,r->str,r->len);
    // Get students' age
    r_students->stu_age = (int *)malloc(r_students->stu_num * sizeof(int));
    if(!r_students->stu_age) {
        cout << "malloc error" << endl;
        exit(-1);
    }
    r = (redisReply *)redisCommand(connect, "LRANGE %s:age 0 -1",key);
    if(r->type == REDIS_REPLY_ERROR) {
        cout << "get_stus error" <<endl;
        exit(-1);
    }
    else if(r->type == REDIS_REPLY_ARRAY) {
        for(int i = 0;i < r_students->stu_num;i++) {
            memcpy(r_students->stu_age + i, r->element[i]->str, r->element[i]->len);
        }
    }
    freeReplyObject(r);
    redisFree(connect);
}

int main() {
    stu stu_a,stu_b;
    stu_a.stu_num = 3;
    int ages[3] = {1,2,3};
    stu_a.stu_age = ages;

    put_stus("test1",stu_a);
    get_stus("test1",&stu_b);

    cout << "stu_b.stu_num is " << stu_b.stu_num << endl;
    for(int i = 0;i < stu_b.stu_num;i++) {
        cout << "stu_b.stu_age[" << i << "] is " << stu_b.stu_age[i] << endl;
    }

}

相关问题