c++ 连接redis 集群 多节点 用户名 密码 selelct 库 的代码
时间: 2024-10-16 16:09:21 浏览: 81
在 C++ 中连接 Redis 集群并设置多个节点、用户名和密码以及选择特定库通常需要使用第三方库,如 `hiredis` 或 `rediactcpp`。这里以 `hiredis` 为例,因为它的 API 相对简洁:
```cpp
#include <hiredis/hiredis.h>
#include <string>
// 定义配置信息
struct RedisConfig {
std::vector<std::pair<std::string, std::string>> nodes; // 节点列表,包括地址和端口
std::string username;
std::string password;
int selected_db; // 选择的数据库索引
};
// 连接函数
redisReply* connectToRedis(const RedisConfig& config) {
redisContext* ctx = nullptr;
for (const auto& node : config.nodes) {
const char* addr = node.first.c_str();
int port = std::stoi(node.second);
// 创建连接
ctx = redisConnect(addr, port);
if (ctx != nullptr && redisStatus(ctx) == REDIS_OK) {
// 设置用户名和密码
if (!config.username.empty()) {
redisReply* auth_reply = redisCommand(ctx, "AUTH %s", config.password.c_str());
if (auth_reply == nullptr || auth_reply->type != REDIS_REPLY_STATUS) {
freeReplyObject(auth_reply);
redisDisconnect(ctx);
ctx = nullptr;
} else {
freeReplyObject(auth_reply);
}
}
// 如果成功,尝试切换到指定库
if (ctx) {
redisReply* select_reply = redisCommand(ctx, "SELECT %d", config.selected_db);
if (select_reply == nullptr || select_reply->type != REDIS_REPLY_INTEGER) {
freeReplyObject(select_reply);
redisDisconnect(ctx);
ctx = nullptr;
} else {
freeReplyObject(select_reply);
}
// 如果所有操作都成功,返回连接上下文
return ctx;
}
} else {
// 失败则断开连接并尝试下一个节点
redisFree(ctx);
ctx = nullptr;
}
}
// 如果所有节点都无法连接,则返回nullptr
return nullptr;
}
int main() {
RedisConfig config = {{"node1.example.com:6379", "node2.example.com:6379"}, "your_username", "your_password", 0};
redisReply* ctx = connectToRedis(config);
if (ctx) {
// 现在你可以使用 ctx 来执行命令
// 示例:redisCommand(ctx, "SET mykey value");
// ...
// 关闭连接
redisFreeReply(ctx);
redisFree(ctx);
} else {
// 错误处理...
}
return 0;
}
```
阅读全文
相关推荐














