我使用HiRedis和一个c/c++程序,并编写了一些测试来验证订阅是否有效(我的解决方案是基于this comment的)。
但是,目前我只能通过在redis-cli终端中手动输入类似于redis-cli的内容来发布。这按照链接注释的方式工作,但我想从我的c++程序中发布。我该怎么做?
我试过这样的命令:
redisAsyncCommand(c, SubCallback, (char*)"command", "publish foo \"abcd\"");但这会导致运行时错误:
错误:只允许错误(P)订阅/(P)取消订阅/退出
如何从HiRedis内部发布数据?
发布于 2015-09-23 14:51:34
一旦订阅了连接上下文,它就不能用于发布。您必须创建一个新连接。
发布于 2015-08-31 05:41:44
来自https://github.com/redis/hiredis in 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;
}https://stackoverflow.com/questions/32302962
复制相似问题