example-ae.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. return;
  21. }
  22. printf("Connected...\n");
  23. }
  24. void disconnectCallback(const redisAsyncContext *c, int status) {
  25. if (status != REDIS_OK) {
  26. printf("Error: %s\n", c->errstr);
  27. return;
  28. }
  29. printf("Disconnected...\n");
  30. }
  31. int main (int argc, char **argv) {
  32. signal(SIGPIPE, SIG_IGN);
  33. redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
  34. if (c->err) {
  35. /* Let *c leak for now... */
  36. printf("Error: %s\n", c->errstr);
  37. return 1;
  38. }
  39. loop = aeCreateEventLoop();
  40. redisAeAttach(loop, c);
  41. redisAsyncSetConnectCallback(c,connectCallback);
  42. redisAsyncSetDisconnectCallback(c,disconnectCallback);
  43. redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
  44. redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
  45. aeMain(loop);
  46. return 0;
  47. }