我正在使用HiRedis和c / c ++程序,并编写了一些测试来验证订阅是否有效(我的解决方案基于this comment)。
但是,目前我只能通过在publish foo "abcd"
终端中手动输入redis-cli
这样的内容来发布。这根据链接的评论工作,但我想从我的c ++程序发布。我怎么能这样做?
我试过这个命令:
redisAsyncCommand(c, SubCallback, (char*)"command", "publish foo \"abcd\"");
但是这导致了这个运行时错误:
错误:仅ERR(P)SUBSCRIBE /(P)在此上下文中允许使用UNSUBSCRIBE / QUIT
如何从HiRedis中发布数据?
答案 0 :(得分:0)
来自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;
}
答案 1 :(得分:0)
连接上下文订阅后,不能用于PUBLISH。您必须创建一个新连接。