example-libevent.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. void getCallback(redisAsyncContext *c, void *r, void *privdata) {
  9. redisReply *reply = r;
  10. if (reply == NULL) return;
  11. printf("argv[%s]: %s\n", (char*)privdata, reply->str);
  12. /* Disconnect after receiving the reply to GET */
  13. redisAsyncDisconnect(c);
  14. }
  15. void connectCallback(const redisAsyncContext *c, int status) {
  16. if (status != REDIS_OK) {
  17. printf("Error: %s\n", c->errstr);
  18. return;
  19. }
  20. printf("Connected...\n");
  21. }
  22. void disconnectCallback(const redisAsyncContext *c, int status) {
  23. if (status != REDIS_OK) {
  24. printf("Error: %s\n", c->errstr);
  25. return;
  26. }
  27. printf("Disconnected...\n");
  28. }
  29. int main (int argc, char **argv) {
  30. signal(SIGPIPE, SIG_IGN);
  31. struct event_base *base = event_base_new();
  32. redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
  33. if (c->err) {
  34. /* Let *c leak for now... */
  35. printf("Error: %s\n", c->errstr);
  36. return 1;
  37. }
  38. redisLibeventAttach(c,base);
  39. redisAsyncSetConnectCallback(c,connectCallback);
  40. redisAsyncSetDisconnectCallback(c,disconnectCallback);
  41. redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
  42. redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
  43. event_base_dispatch(base);
  44. return 0;
  45. }