example-ae.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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/ae.h>
  8. /* Put event loop in the global scope, so it can be explicitly stopped */
  9. static aeEventLoop *loop;
  10. void getCallback(redisAsyncContext *c, void *r, void *privdata) {
  11. redisReply *reply = r;
  12. if (reply == NULL) return;
  13. printf("argv[%s]: %s\n", (char*)privdata, reply->str);
  14. /* Disconnect after receiving the reply to GET */
  15. redisAsyncDisconnect(c);
  16. }
  17. void connectCallback(const redisAsyncContext *c, int status) {
  18. if (status != REDIS_OK) {
  19. printf("Error: %s\n", c->errstr);
  20. aeStop(loop);
  21. return;
  22. }
  23. printf("Connected...\n");
  24. }
  25. void disconnectCallback(const redisAsyncContext *c, int status) {
  26. if (status != REDIS_OK) {
  27. printf("Error: %s\n", c->errstr);
  28. aeStop(loop);
  29. return;
  30. }
  31. printf("Disconnected...\n");
  32. aeStop(loop);
  33. }
  34. int main (int argc, char **argv) {
  35. signal(SIGPIPE, SIG_IGN);
  36. redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
  37. if (c->err) {
  38. /* Let *c leak for now... */
  39. printf("Error: %s\n", c->errstr);
  40. return 1;
  41. }
  42. loop = aeCreateEventLoop(64);
  43. redisAeAttach(loop, c);
  44. redisAsyncSetConnectCallback(c,connectCallback);
  45. redisAsyncSetDisconnectCallback(c,disconnectCallback);
  46. redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
  47. redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
  48. aeMain(loop);
  49. return 0;
  50. }