无法将键设置为'redisClusterCommand()'返回空指针

时间:2019-03-19 10:16:58

标签: 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]Error: ctx get by node is null

1 个答案:

答案 0 :(得分:0)

我在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);
}