1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <signal.h>
5
6 #include <hiredis.h>
7 #include <async.h>
8 #include <adapters/libevent.h>
9
getCallback(redisAsyncContext * c,void * r,void * privdata)10 void getCallback(redisAsyncContext *c, void *r, void *privdata) {
11 redisReply *reply = r;
12 if (reply == NULL) {
13 if (c->errstr) {
14 printf("errstr: %s\n", c->errstr);
15 }
16 return;
17 }
18 printf("argv[%s]: %s\n", (char*)privdata, reply->str);
19
20 /* Disconnect after receiving the reply to GET */
21 redisAsyncDisconnect(c);
22 }
23
connectCallback(const redisAsyncContext * c,int status)24 void connectCallback(const redisAsyncContext *c, int status) {
25 if (status != REDIS_OK) {
26 printf("Error: %s\n", c->errstr);
27 return;
28 }
29 printf("Connected...\n");
30 }
31
disconnectCallback(const redisAsyncContext * c,int status)32 void disconnectCallback(const redisAsyncContext *c, int status) {
33 if (status != REDIS_OK) {
34 printf("Error: %s\n", c->errstr);
35 return;
36 }
37 printf("Disconnected...\n");
38 }
39
main(int argc,char ** argv)40 int main (int argc, char **argv) {
41 signal(SIGPIPE, SIG_IGN);
42 struct event_base *base = event_base_new();
43 redisOptions options = {0};
44 REDIS_OPTIONS_SET_TCP(&options, "127.0.0.1", 6379);
45 struct timeval tv = {0};
46 tv.tv_sec = 1;
47 options.timeout = &tv;
48
49
50 redisAsyncContext *c = redisAsyncConnectWithOptions(&options);
51 if (c->err) {
52 /* Let *c leak for now... */
53 printf("Error: %s\n", c->errstr);
54 return 1;
55 }
56
57 redisLibeventAttach(c,base);
58 redisAsyncSetConnectCallback(c,connectCallback);
59 redisAsyncSetDisconnectCallback(c,disconnectCallback);
60 redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
61 redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
62 event_base_dispatch(base);
63 return 0;
64 }
65