redis怎么插入一个struct结构
时间: 2023-07-01 12:15:30 浏览: 62
在Redis中,可以通过将一个结构体序列化为字符串,然后将其作为一个字符串类型的值插入Redis中。常见的序列化方式包括JSON、MessagePack、Protobuf等。
以下是一个使用JSON序列化和插入一个struct结构体的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h>
#include <jansson.h>
typedef struct {
int id;
char name[20];
float price;
} Product;
int main(void) {
// 初始化Redis连接
redisContext *ctx = redisConnect("127.0.0.1", 6379);
if (ctx == NULL || ctx->err) {
if (ctx) {
printf("Error: %s\n", ctx->errstr);
redisFree(ctx);
} else {
printf("Can't allocate redis context\n");
}
exit(1);
}
// 创建一个Product结构体对象
Product p = {
.id = 1001,
.name = "Apple",
.price = 5.99
};
// 将Product结构体序列化为JSON字符串
json_t *json = json_pack("{s:i, s:s, s:f}",
"id", p.id,
"name", p.name,
"price", p.price);
char *json_str = json_dumps(json, JSON_COMPACT);
json_decref(json);
// 插入JSON字符串到Redis
redisReply *reply = redisCommand(ctx, "SET %d %s", p.id, json_str);
free(json_str);
if (reply == NULL) {
printf("Error: %s\n", ctx->errstr);
redisFree(ctx);
exit(1);
}
freeReplyObject(reply);
// 从Redis中读取JSON字符串并反序列化为Product对象
reply = redisCommand(ctx, "GET %d", p.id);
if (reply == NULL) {
printf("Error: %s\n", ctx->errstr);
redisFree(ctx);
exit(1);
}
json_error_t error;
json_t *root = json_loads(reply->str, 0, &error);
if (!root) {
printf("Error: %s\n", error.text);
freeReplyObject(reply);
redisFree(ctx);
exit(1);
}
p.id = json_integer_value(json_object_get(root, "id"));
strcpy(p.name, json_string_value(json_object_get(root, "name")));
p.price = json_real_value(json_object_get(root, "price"));
json_decref(root);
freeReplyObject(reply);
// 打印Product对象
printf("Product ID: %d\n", p.id);
printf("Product Name: %s\n", p.name);
printf("Product Price: %.2f\n", p.price);
// 释放Redis连接
redisFree(ctx);
return 0;
}
```
在上述示例中,我们先创建了一个Product结构体对象p,然后将其序列化为JSON字符串json_str,并插入到Redis中。之后,我们从Redis中读取JSON字符串,然后反序列化为Product对象。最后,我们打印了Product对象的属性。