对不起,我之前的回答有误。确实可以使用 redisConnectWithPassword
函数来连接需要密码的 Redis 服务器。以下是正确的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>
int main() {
const char *password = "your_password"; // 替换为你的密码
redisContext *context = redisConnectWithPassword("127.0.0.1", 6379, password);
// 检查连接是否成功
if (context == NULL || context->err) {
if (context) {
printf("Error: %s\n", context->errstr);
redisFree(context);
} else {
printf("Can't allocate redis context\n");
}
return EXIT_FAILURE;
}
// 执行命令,例如设置和获取键值对
redisCommand(context, "SET foo bar");
redisReply *reply = redisCommand(context, "GET foo");
if (reply && reply->type == REDIS_REPLY_STRING) {
printf("foo: %s\n", reply->str);
}
// 清理资源
freeReplyObject(reply);
redisFree(context);
return EXIT_SUCCESS;
}
编译与运行
编译时确保链接到 hiredis
库:
gcc example.c -o example -lhiredis
然后运行程序:
./example
请确保替换 "your_password"
为你实际的 Redis 密码。这样,程序会使用指定的密码进行连接。如果还有其他问题,请随时问我!
内容由零声教学AI助手提供,问题来源于学员提问