c++ - 无法设置 key ,因为 'redisClusterCommand()' 正在返回空指针

标签 c++ c redis hiredis

我正在尝试运行一个简单的程序,它将一个键值插入到我的 6 个实例(3 个主实例,3 个拷贝)的 redis 集群中。我正在使用 hiredis-vip .

程序如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hircluster.h>

int main(int argc, char **argv) 
{
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
redisClusterContext *cc = redisClusterContextInit();
redisClusterSetOptionAddNodes(cc, "172.16.129.68:6379");
redisClusterSetOptionConnectTimeout(cc, timeout);
redisClusterConnect2(cc);
if (cc != NULL && cc->err) {
    printf("Error: %s\n", cc->errstr);
    // handle error
exit(-1);
}
redisReply *reply;
    reply = (redisReply*)(redisClusterCommand(cc,"SET %s %s", "foo", "hello vishal"));
    printf("SET: %s\n", reply->str);
    freeReplyObject(reply);
    redisClusterFree(cc);
    return 0;
}

在运行程序时,出现段错误:

Program received signal SIGSEGV, Segmentation fault.
0x00000000004009ed in main (argc=1, argv=0x7fffffffe508) at cluster-example.c:30
30          printf("SET: %s\n", reply->str);
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.209.el6_9.2.x86_64 libgcc-4.4.7-18.el6_9.2.x86_64 libstdc++-4.4.7-18.el6_9.2.x86_64
(gdb) bt f
#0  0x00000000004009ed in main (argc=1, argv=0x7fffffffe508) at cluster-example.c:30
        timeout = {tv_sec = 1, tv_usec = 500000}
        cc = 0x7ffff7fdb010
        reply = 0x0

redisReply * 具有 NULL 值,当我在 printf() 中使用此指针时会导致段错误。

程序有什么问题?

编辑 1

根据@Stamatis Liatsos 的建议,我更新了部分程序:

    reply = (redisReply*)(redisClusterCommand(cc,"SET %s %s", "foo", "hello vishal"));
if(cc->err)
    printf("\n[%s::%d]Error: %s\n", __FILE__,__LINE__,cc->errstr);
else
    printf("SET: %s\n", reply->str);

这是我得到的输出:

[cluster-example.c::31]错误:节点获取的ctx为空

最佳答案

我在 here 上找到了这个问题的解决方案.

我们必须在连接之前设置上下文以使用插槽。

struct timeval timeout = { 1, 500000 }; // 1.5 seconds
redisClusterContext *cc = redisClusterContextInit();
redisClusterSetOptionAddNodes(cc, "172.16.129.68:6379");
redisClusterSetOptionConnectTimeout(cc, timeout);
redisClusterSetOptionRouteUseSlots(cc);  //The function that has to be called.
redisClusterConnect2(cc);
if (cc != NULL && cc->err) {
    printf("Error: %s\n", cc->errstr);
    // handle error
exit(-1);
}

关于c++ - 无法设置 key ,因为 'redisClusterCommand()' 正在返回空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55238533/

相关文章:

c++ - 指向指针数组和指针数组的区别

c++ - 在 C++ 中将美元转换为美分

c++ - 当复制构造函数是私有(private)的且未实现时是否允许 RVO?

c - 从文本行的两侧删除空格

api - 我可以从 URL 中提取本地 Redis 数据吗?

c++ - 在指定 C++ 异常和 pthread 取消的交互方面有什么进展吗?

c - 排列数组中的数字

c++ - 以编程方式生成一个 Redis 实例

amazon-web-services - 在 aws-elasticache 上使用 memcached 或 Redis

c - getopt 在 C 中添加额外功能