example.c 2.2 KB

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