2
0

example.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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.2", 6379, timeout);
  11. if (c->err) {
  12. printf("Connection error: %s\n", c->errstr);
  13. exit(1);
  14. }
  15. /* PING server */
  16. reply = redisCommand(c,"PING");
  17. printf("PING: %s\n", reply->str);
  18. freeReplyObject(reply);
  19. /* Set a key */
  20. reply = redisCommand(c,"SET %s %s", "foo", "hello world");
  21. printf("SET: %s\n", reply->str);
  22. freeReplyObject(reply);
  23. /* Set a key using binary safe API */
  24. reply = redisCommand(c,"SET %b %b", "bar", 3, "hello", 5);
  25. printf("SET (binary API): %s\n", reply->str);
  26. freeReplyObject(reply);
  27. /* Try a GET and two INCR */
  28. reply = redisCommand(c,"GET foo");
  29. printf("GET foo: %s\n", reply->str);
  30. freeReplyObject(reply);
  31. reply = redisCommand(c,"INCR counter");
  32. printf("INCR counter: %lld\n", reply->integer);
  33. freeReplyObject(reply);
  34. /* again ... */
  35. reply = redisCommand(c,"INCR counter");
  36. printf("INCR counter: %lld\n", reply->integer);
  37. freeReplyObject(reply);
  38. /* Create a list of numbers, from 0 to 9 */
  39. reply = redisCommand(c,"DEL mylist");
  40. freeReplyObject(reply);
  41. for (j = 0; j < 10; j++) {
  42. char buf[64];
  43. snprintf(buf,64,"%d",j);
  44. reply = redisCommand(c,"LPUSH mylist element-%s", buf);
  45. freeReplyObject(reply);
  46. }
  47. /* Let's check what we have inside the list */
  48. reply = redisCommand(c,"LRANGE mylist 0 -1");
  49. if (reply->type == REDIS_REPLY_ARRAY) {
  50. for (j = 0; j < reply->elements; j++) {
  51. printf("%u) %s\n", j, reply->element[j]->str);
  52. }
  53. }
  54. freeReplyObject(reply);
  55. return 0;
  56. }