1 #include <stdlib.h>
2 
3 #include <hiredis.h>
4 #include <async.h>
5 #include <adapters/glib.h>
6 
7 static GMainLoop *mainloop;
8 
9 static void
connect_cb(const redisAsyncContext * ac G_GNUC_UNUSED,int status)10 connect_cb (const redisAsyncContext *ac G_GNUC_UNUSED,
11             int status)
12 {
13     if (status != REDIS_OK) {
14         g_printerr("Failed to connect: %s\n", ac->errstr);
15         g_main_loop_quit(mainloop);
16     } else {
17         g_printerr("Connected...\n");
18     }
19 }
20 
21 static void
disconnect_cb(const redisAsyncContext * ac G_GNUC_UNUSED,int status)22 disconnect_cb (const redisAsyncContext *ac G_GNUC_UNUSED,
23                int status)
24 {
25     if (status != REDIS_OK) {
26         g_error("Failed to disconnect: %s", ac->errstr);
27     } else {
28         g_printerr("Disconnected...\n");
29         g_main_loop_quit(mainloop);
30     }
31 }
32 
33 static void
command_cb(redisAsyncContext * ac,gpointer r,gpointer user_data G_GNUC_UNUSED)34 command_cb(redisAsyncContext *ac,
35            gpointer r,
36            gpointer user_data G_GNUC_UNUSED)
37 {
38     redisReply *reply = r;
39 
40     if (reply) {
41         g_print("REPLY: %s\n", reply->str);
42     }
43 
44     redisAsyncDisconnect(ac);
45 }
46 
47 gint
main(gint argc G_GNUC_UNUSED,gchar * argv[]G_GNUC_UNUSED)48 main (gint argc     G_GNUC_UNUSED,
49       gchar *argv[] G_GNUC_UNUSED)
50 {
51     redisAsyncContext *ac;
52     GMainContext *context = NULL;
53     GSource *source;
54 
55     ac = redisAsyncConnect("127.0.0.1", 6379);
56     if (ac->err) {
57         g_printerr("%s\n", ac->errstr);
58         exit(EXIT_FAILURE);
59     }
60 
61     source = redis_source_new(ac);
62     mainloop = g_main_loop_new(context, FALSE);
63     g_source_attach(source, context);
64 
65     redisAsyncSetConnectCallback(ac, connect_cb);
66     redisAsyncSetDisconnectCallback(ac, disconnect_cb);
67     redisAsyncCommand(ac, command_cb, NULL, "SET key 1234");
68     redisAsyncCommand(ac, command_cb, NULL, "GET key");
69 
70     g_main_loop_run(mainloop);
71 
72     return EXIT_SUCCESS;
73 }
74