/hiredis/example.c

http://github.com/nicolasff/webdis · C · 73 lines · 54 code · 12 blank · 7 comment · 9 complexity · 85c269055ffbb1ddb17e7365576b8e7e MD5 · raw file

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "hiredis.h"
  5. int main(void) {
  6. unsigned int j;
  7. redisContext *c;
  8. redisReply *reply;
  9. struct timeval timeout = { 1, 500000 }; // 1.5 seconds
  10. c = redisConnectWithTimeout((char*)"127.0.0.1", 6379, timeout);
  11. if (c == NULL || c->err) {
  12. if (c) {
  13. printf("Connection error: %s\n", c->errstr);
  14. redisFree(c);
  15. } else {
  16. printf("Connection error: can't allocate redis context\n");
  17. }
  18. exit(1);
  19. }
  20. /* PING server */
  21. reply = redisCommand(c,"PING");
  22. printf("PING: %s\n", reply->str);
  23. freeReplyObject(reply);
  24. /* Set a key */
  25. reply = redisCommand(c,"SET %s %s", "foo", "hello world");
  26. printf("SET: %s\n", reply->str);
  27. freeReplyObject(reply);
  28. /* Set a key using binary safe API */
  29. reply = redisCommand(c,"SET %b %b", "bar", 3, "hello", 5);
  30. printf("SET (binary API): %s\n", reply->str);
  31. freeReplyObject(reply);
  32. /* Try a GET and two INCR */
  33. reply = redisCommand(c,"GET foo");
  34. printf("GET foo: %s\n", reply->str);
  35. freeReplyObject(reply);
  36. reply = redisCommand(c,"INCR counter");
  37. printf("INCR counter: %lld\n", reply->integer);
  38. freeReplyObject(reply);
  39. /* again ... */
  40. reply = redisCommand(c,"INCR counter");
  41. printf("INCR counter: %lld\n", reply->integer);
  42. freeReplyObject(reply);
  43. /* Create a list of numbers, from 0 to 9 */
  44. reply = redisCommand(c,"DEL mylist");
  45. freeReplyObject(reply);
  46. for (j = 0; j < 10; j++) {
  47. char buf[64];
  48. snprintf(buf,64,"%d",j);
  49. reply = redisCommand(c,"LPUSH mylist element-%s", buf);
  50. freeReplyObject(reply);
  51. }
  52. /* Let's check what we have inside the list */
  53. reply = redisCommand(c,"LRANGE mylist 0 -1");
  54. if (reply->type == REDIS_REPLY_ARRAY) {
  55. for (j = 0; j < reply->elements; j++) {
  56. printf("%u) %s\n", j, reply->element[j]->str);
  57. }
  58. }
  59. freeReplyObject(reply);
  60. return 0;
  61. }