redis - Hiredis waiting for message -
i using hiredis c library connect redis server. not able figure out how wait new messages after subscribing new message.
my code like:
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 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"); redisasynccommand(c, getcallback, (char*) "end-1", "subscribe foo");
now how tell hiredis wait message on channel ?
you not have tell hiredis need wait on channel: event loop wait on redis connection has been registered.
here complete example:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include "hiredis.h" #include "async.h" #include "adapters/libevent.h" void subcallback(redisasynccontext *c, void *r, void *priv) { redisreply *reply = r; if (reply == null) return; if ( reply->type == redis_reply_array && reply->elements == 3 ) { if ( strcmp( reply->element[0]->str, "subscribe" ) != 0 ) { printf( "received[%s] channel %s: %s\n", (char*)priv, reply->element[1]->str, reply->element[2]->str ); } } } 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 now... */ printf("error: %s\n", c->errstr); return 1; } redislibeventattach(c,base); redisasyncsetconnectcallback(c,connectcallback); redisasyncsetdisconnectcallback(c,disconnectcallback); redisasynccommand(c, subcallback, (char*) "sub", "subscribe foo"); event_base_dispatch(base); return 0; }
you can test use following command publish something:
redis-cli publish foo
the event_base_dispatch function 1 launches event loop, , makes wait on redis subscription.