example.c 2.6 KB

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