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