在使用 hiredis 库进行 Redis 数据库连接时,可以通过以下方式添加 IP、端口、用户和密码配置:
- 配置 IP 和端口:
redisContext *ctx = redisConnect("127.0.0.1", 6379); // 替换为你的 Redis 服务器 IP 和端口
if (ctx == NULL || ctx->err) {
if (ctx) {
printf("Error: %s\n", ctx->errstr);
// 处理连接错误的逻辑
} else {
printf("Can't allocate redis context\n");
// 处理内存分配错误的逻辑
}
return;
}
- 配置用户和密码:
redisContext *ctx = redisConnectWithTimeout("127.0.0.1", 6379, timeout); // 替换为你的 Redis 服务器 IP 和端口
if (ctx == NULL || ctx->err) {
if (ctx) {
printf("Error: %s\n", ctx->errstr);
// 处理连接错误的逻辑
} else {
printf("Can't allocate redis context\n");
// 处理内存分配错误的逻辑
}
return;
}
// 进行身份验证(用户名和密码)
redisReply *reply = (redisReply *)redisCommand(ctx, "AUTH your_password"); // 替换为你的 Redis 密码
if (reply == NULL || reply->type == REDIS_REPLY_ERROR) {
printf("Authentication failed: %s\n", reply ? reply->str : "NULL");
freeReplyObject(reply);
return;
}
freeReplyObject(reply);
注意:上述代码中的 “127.0.0.1” 和 6379 是示例,需要替换为你实际使用的 Redis 服务器 IP 和端口。同时,“your_password”也需要替换为你的 Redis 密码。
内容由零声教学AI助手提供,问题来源于学员提问