2

我正在将 HiRedis 与 ac/c++ 程序一起使用,并编写了一些测试来验证订阅是否有效(我的解决方案基于此评论)。

但是,目前我只能通过在终端中手动输入类似publish foo "abcd"redis-cli内容来发布。这根据链接的评论起作用,但我想我的 c++ 程序中发布。我怎样才能做到这一点?

我试过这个命令:

redisAsyncCommand(c, SubCallback, (char*)"command", "publish foo \"abcd\"");

但这会导致此运行时错误:

错误:在此上下文中仅允许 ERR (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT

如何从 HiRedis 中发布数据?

4

2 回答 2

1

一旦订阅了连接上下文,它就不能用于 PUBLISH。您必须创建一个新连接。

于 2015-09-23T14:51:34.667 回答
-1

来自:https://github.com/redis/hiredis_hiredis/examples/example-libevent.c

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

#include <hiredis.h>
#include <async.h>
#include <adapters/libevent.h>

void getCallback(redisAsyncContext *c, void *r, void *privdata) {
    redisReply *reply = r;
    if (reply == NULL) return;
    printf("argv[%s]: %s\n", (char*)privdata, reply->str);

    /* Disconnect after receiving the reply to GET */
    redisAsyncDisconnect(c);
}

void connectCallback(const redisAsyncContext *c, int status) {
    if (status != REDIS_OK) {
        printf("Error: %s\n", c->errstr);
        return;
    }
    printf("Connected...\n");
}

void disconnectCallback(const redisAsyncContext *c, int status) {
    if (status != REDIS_OK) {
        printf("Error: %s\n", c->errstr);
        return;
    }
    printf("Disconnected...\n");
}

int main (int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);
    struct event_base *base = event_base_new();

    redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
    if (c->err) {
        /* Let *c leak for now... */
        printf("Error: %s\n", c->errstr);
        return 1;
    }

    redisLibeventAttach(c,base);
    redisAsyncSetConnectCallback(c,connectCallback);
    redisAsyncSetDisconnectCallback(c,disconnectCallback);
    redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
    redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
    event_base_dispatch(base);
    return 0;
}
于 2015-08-31T05:41:44.397 回答