ZBLOG

不是用redisConnectWithPassword 函数吗

对不起,我之前的回答有误。确实可以使用 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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=22358

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?