以下是一个示例代码,演示如何在C++中查找和更新Redis中的嵌套哈希:
#include <iostream>
#include <hiredis/hiredis.h>
int main() {
redisContext* redis = redisConnect("localhost", 6379); // 连接到本地Redis服务器
if (redis == NULL || redis->err) {
std::cout << "连接到Redis失败: " << redis->errstr << std::endl;
return 1;
}
// 示例数据
std::string hashKey = "myhash";
std::string subHashKey = "subhash";
std::string nestedHashKey = "nestedhash";
// 设置嵌套哈希值
redisReply* reply = (redisReply*)redisCommand(redis, "HSET %s:%s:%s name John", hashKey.c_str(), subHashKey.c_str(), nestedHashKey.c_str());
if (reply->type == REDIS_REPLY_ERROR) {
std::cout << "设置嵌套哈希值时出错: " << reply->str << std::endl;
freeReplyObject(reply);
return 1;
}
// 获取嵌套哈希值
reply = (redisReply*)redisCommand(redis, "HGET %s:%s:%s name", hashKey.c_str(), subHashKey.c_str(), nestedHashKey.c_str());
if (reply->type == REDIS_REPLY_STRING) {
std::cout << "获取到的嵌套哈希值为: " << reply->str << std::endl;
} else {
std::cout << "获取嵌套哈希值时出错: " << reply->str << std::endl;
}
freeReplyObject(reply);
// 更新嵌套哈希值
reply = (redisReply*)redisCommand(redis, "HSET %s:%s:%s name Tom", hashKey.c_str(), subHashKey.c_str(), nestedHashKey.c_str());
if (reply->type == REDIS_REPLY_ERROR) {
std::cout << "更新嵌套哈希值时出错: " << reply->str << std::endl;
freeReplyObject(reply);
return 1;
}
// 再次获取嵌套哈希值,验证是否更新成功
reply = (redisReply*)redisCommand(redis, "HGET %s:%s:%s name", hashKey.c_str(), subHashKey.c_str(), nestedHashKey.c_str());
if (reply->type == REDIS_REPLY_STRING) {
std::cout << "更新后的嵌套哈希值为: " << reply->str << std::endl;
} else {
std::cout << "获取嵌套哈希值时出错: " << reply->str << std::endl;
}
freeReplyObject(reply);
redisFree(redis); // 断开与Redis服务器的连接
return 0;
}
请确保已经安装 hiredis 库,并在编译时链接该库(例如:-lhiredis)。
此示例连接到本地 Redis 服务器,在指定的嵌套哈希中设置和获取键名为 name 的子键的值。
内容由零声教学AI助手提供,问题来源于学员提问




