2
0

example-glib.c 1.6 KB

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