hiredis 訂閱發佈

原文鏈接:https://blog.csdn.net/sahusoft/article/details/9428347

hiredis發佈/訂閱示例

 

轉:https://blog.csdn.net/sahusoft/article/details/9428347

代碼:

  1. #include <stdio.h>

  2. #include <stdlib.h>

  3. #include <string.h>

  4. #include <signal.h>

  5. #include "hiredis.h"

  6. #include "async.h"

  7. #include "adapters/libevent.h"

  8.  
  9. void subCallback(redisAsyncContext *c, void *r, void *priv) {

  10. redisReply *reply = r;

  11. if (reply == NULL) return;

  12. if ( reply->type == REDIS_REPLY_ARRAY && reply->elements == 3 ) {

  13. if ( strcmp( reply->element[0]->str, "subscribe" ) != 0 ) {

  14. printf( "Received[%s] channel %s: %s\n",

  15. (char*)priv,

  16. reply->element[1]->str,

  17. reply->element[2]->str );

  18. }

  19. }

  20. }

  21.  
  22. void connectCallback(const redisAsyncContext *c, int status) {

  23. if (status != REDIS_OK) {

  24. printf("Error: %s\n", c->errstr);

  25. return;

  26. }

  27. printf("Connected...\n");

  28. }

  29.  
  30. void disconnectCallback(const redisAsyncContext *c, int status) {

  31. if (status != REDIS_OK) {

  32. printf("Error: %s\n", c->errstr);

  33. return;

  34. }

  35. printf("Disconnected...\n");

  36. }

  37.  
  38. int main (int argc, char **argv) {

  39. signal(SIGPIPE, SIG_IGN);

  40. struct event_base *base = event_base_new();

  41.  
  42. redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);

  43. if (c->err) {

  44. /* Let *c leak for now... */

  45. printf("Error: %s\n", c->errstr);

  46. return 1;

  47. }

  48.  
  49. redisLibeventAttach(c,base);

  50. redisAsyncSetConnectCallback(c,connectCallback);

  51. redisAsyncSetDisconnectCallback(c,disconnectCallback);

  52. redisAsyncCommand(c, subCallback, (char*) "sub", "SUBSCRIBE foo");

  53.  
  54. event_base_dispatch(base);

  55. return 0;

  56. }

 

編譯:

gcc example-subpub.c libhiredis.a adapters/libevent.h -levent

 

測試:

訂閱端

./a.out

發佈端

./redis-cli PUBLISH foo bar

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章