ZBLOG

不是用redisConnectWithPassword 函数吗

对不起,我之前的回答有误。确实可以使用 redisConnectWithPassword 函数来连接需要密码的 Redis 服务器。以下是正确的示例代码:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <hiredis/hiredis.h>
  4. int main() {
  5. const char *password = "your_password"; // 替换为你的密码
  6. redisContext *context = redisConnectWithPassword("127.0.0.1", 6379, password);
  7. // 检查连接是否成功
  8. if (context == NULL || context->err) {
  9. if (context) {
  10. printf("Error: %s\n", context->errstr);
  11. redisFree(context);
  12. } else {
  13. printf("Can't allocate redis context\n");
  14. }
  15. return EXIT_FAILURE;
  16. }
  17. // 执行命令,例如设置和获取键值对
  18. redisCommand(context, "SET foo bar");
  19. redisReply *reply = redisCommand(context, "GET foo");
  20. if (reply && reply->type == REDIS_REPLY_STRING) {
  21. printf("foo: %s\n", reply->str);
  22. }
  23. // 清理资源
  24. freeReplyObject(reply);
  25. redisFree(context);
  26. return EXIT_SUCCESS;
  27. }

编译与运行

编译时确保链接到 hiredis 库:

  1. gcc example.c -o example -lhiredis

然后运行程序:

  1. ./example

请确保替换 "your_password" 为你实际的 Redis 密码。这样,程序会使用指定的密码进行连接。如果还有其他问题,请随时问我!


内容由零声教学AI助手提供,问题来源于学员提问

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?