reids 存取c语言结构体数据

#include <hiredis/hiredis.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;

struct Person{
    int id;
    char name[50];
    int age;
};

int main() {
    Person p = {11, "Alice", 25};
    
    // 连接Redis服务
    redisContext *context = redisConnect("127.0.0.1", 6379);
    if (context == NULL || context->err) {
        if (context) {
            printf("%s\n", context->errstr);
        } else {
            printf("redisConnect error\n");
        }
        exit(EXIT_FAILURE);
    }

    //执行命令
    // Set Key Value
    char *key = "pkey";
    
    /*SET key value */
    redisReply * reply = (redisReply *)redisCommand(context, "SET %b %b",&key, 4 ,&p, sizeof(Person) );
    std::cout<<"len:"<<sizeof(Person);
    printf("type : %d\n", reply->type);
    if (reply->type == REDIS_REPLY_STATUS) {
        /*SET str Hello World*/
        printf("SET %s \n", key);
    }
    freeReplyObject(reply);
 
    // // GET Key
    reply = (redisReply *)redisCommand(context, "GET %b", &key, 4);
    Person *p2 = (Person *)(reply->str);
    printf("out    %d %s %d\n", p2->id, p2->name, p2->age);


    printf("GET len %ld\n", reply->len);

    freeReplyObject(reply);
 
//释放连接
    redisFree(context);
    return EXIT_SUCCESS;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值