example-libevent.c 1.7 KB

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