上图是本文要实现的功能,用到了RapidJson和cpp_redis两个库。
代码如下:
#include <iostream>
#include <list>
using namespace std;
#include <cpp_redis/cpp_redis>
#include "JsonObject.h"
#include "Person.h"
#ifdef _WIN32
#include <Winsock2.h>
#endif /* _WIN32 */
#pragma comment( lib, "ws2_32.lib")//最好的方法是包含在项目属性中,因为那样可以根据Debug、Release、x86、x64来区分。这里仅仅是为了突出引用了这个库写在这里
bool StartWSA(void)
{
//! Windows netword DLL init
WORD version = MAKEWORD(2, 2);
WSADATA data;
if (WSAStartup(version, &data) != 0)
{
std::cerr << "WSAStartup() failure" << std::endl;
return false;
}
return true;
}
void StopWSA(void)
{
WSACleanup();
}
void cpp_redis_connect(cpp_redis::redis_client& _client)
{
//! Enable logging
cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);
_client.connect("127.0.0.1", 6379, [](cpp_redis::redis_client&)
{
std::cout << "client disconnected (disconnection handler)" << std::endl;
});
}
int main(int argc, char* argv[])
{
//启动Windows网络通信库
if (!StartWSA())
{
return -1;
}
try
{
cpp_redis::redis_client client;
cpp_redis_connect(client);
//创建C++类对象
std::list<Employee> employees;
employees.push_back(Employee("Milo YIP", 34, true));
employees.back().AddDependent(Dependent("Lua YIP", 3, new Education("Happy Kindergarten", 3.5)));
employees.back().AddDependent(Dependent("Mio YIP", 1));
employees.push_back(Employee("Percy TSE", 30, false));
std::vector<string> allKeysList;
//将C++类对象序列化之后,发送到redis服务器
vector<pair<string, string>> vecPair /*= { { "key1", "value1" },{ "key2", "value2" },{ "key3", "value3" } }*/;
for (auto itr = employees.begin(); itr != employees.end(); ++itr)
{
vecPair.push_back(std::make_pair(itr->GetRedisKey(), itr->ToJson()));
allKeysList.push_back(itr->GetRedisKey());
}
//新增:批量
client.hmset("MyHashSet", vecPair, [&](cpp_redis::reply& _reply) {
std::cout << "往redis发送数据:HashSet,主键MyHashSet " << _reply << endl;
});
//从redis取出json字符串反序列化为C++内存对象
std::list<Employee> employeesFromRedis;
for each (auto& var in allKeysList)
{
//查询:单个
client.hget("MyHashSet", var.c_str(), [&](cpp_redis::reply& _reply)
{
std::cout << "在redis的Hash容器中查询单个:容器名称[MyHashSet] key[" << var <<"]" << endl << "结果:" << _reply.as_string() << endl;
Employee employee;
employee.CreateFromJson(_reply.as_string().c_str());
employeesFromRedis.push_back(employee);
});
}
// synchronous commit 同步提交:将上面的所有get set 等方法依次执行完, no timeout
client.sync_commit();
cout << "从redis取回的字符串反序列化得到的C++对象调用ToJson得到的结果:" << endl;
for (auto itr = employeesFromRedis.begin(); itr != employeesFromRedis.end(); ++itr)
{
cout << itr->ToJson() << endl;
}
}
catch (cpp_redis::redis_error e)
{
std::cout << e.what() << endl;
}
//关闭Windows网络通信库
StopWSA();
return 0;
}
程序验证输出如下(完全正确):
工程资源文件:
百度云链接 欢迎加我哦