用C++实现redis插入一个结构体
时间: 2023-07-18 21:12:05 浏览: 60
在C++中,也可以通过将一个结构体序列化为字符串,然后将其作为一个字符串类型的值插入Redis中。常见的序列化方式包括JSON、MessagePack、Protobuf等。
以下是一个使用JSON序列化和插入一个struct结构体的示例:
```c++
#include <iostream>
#include <string>
#include <cstring>
#include <hiredis/hiredis.h>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
struct Product {
int id;
std::string name;
float price;
};
int main() {
// 初始化Redis连接
redisContext *ctx = redisConnect("127.0.0.1", 6379);
if (ctx == NULL || ctx->err) {
if (ctx) {
std::cout << "Error: " << ctx->errstr << std::endl;
redisFree(ctx);
} else {
std::cout << "Can't allocate redis context" << std::endl;
}
exit(1);
}
// 创建一个Product结构体对象
Product p = {
.id = 1001,
.name = "Apple",
.price = 5.99
};
// 将Product结构体序列化为JSON字符串
json j = {
{"id", p.id},
{"name", p.name},
{"price", p.price}
};
std::string json_str = j.dump();
// 插入JSON字符串到Redis
redisReply *reply = (redisReply*)redisCommand(ctx, "SET %d %s", p.id, json_str.c_str());
if (reply == NULL) {
std::cout << "Error: " << ctx->errstr << std::endl;
redisFree(ctx);
exit(1);
}
freeReplyObject(reply);
// 从Redis中读取JSON字符串并反序列化为Product对象
reply = (redisReply*)redisCommand(ctx, "GET %d", p.id);
if (reply == NULL) {
std::cout << "Error: " << ctx->errstr << std::endl;
redisFree(ctx);
exit(1);
}
std::string json_reply(reply->str, reply->len);
json j_reply = json::parse(json_reply);
p.id = j_reply["id"];
p.name = j_reply["name"];
p.price = j_reply["price"];
freeReplyObject(reply);
// 打印Product对象
std::cout << "Product ID: " << p.id << std::endl;
std::cout << "Product Name: " << p.name << std::endl;
std::cout << "Product Price: " << p.price << std::endl;
// 释放Redis连接
redisFree(ctx);
return 0;
}
```
在上述示例中,我们使用了第三方JSON库nlohmann/json来序列化和反序列化JSON字符串。我们先创建了一个Product结构体对象p,然后将其序列化为JSON字符串json_str,并插入到Redis中。之后,我们从Redis中读取JSON字符串,然后反序列化为Product对象。最后,我们打印了Product对象的属性。需要注意的是,在C++中需要将字符串类型的返回值转换为std::string类型的变量。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)