example.c 2.5 KB

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