redis.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #ifndef REDIS_H
  2. #define REDIS_H
  3. #include <stdio.h>
  4. #include <QString>
  5. #include <string.h>
  6. #include <stddef.h>
  7. #include <stdarg.h>
  8. #include <string.h>
  9. #include <assert.h>
  10. #include <hiredis/hiredis.h>
  11. #define REDIS_HOST "127.0.0.1"
  12. #define REDIS_PORT 6379
  13. redisContext *c = NULL;
  14. int redisconnected;
  15. int redis_init()
  16. {
  17. c = redisConnect(REDIS_HOST, REDIS_PORT);
  18. if (NULL == c || c->err) {
  19. if(c) {
  20. printf("Redis [%s:%d], Error:[%s]\n", REDIS_HOST, REDIS_PORT, c->errstr);
  21. redisFree(c);
  22. } else {
  23. printf("Redis [%s:%d] failure\n", REDIS_HOST, REDIS_PORT);
  24. }
  25. return -1;
  26. }
  27. return 0;
  28. }
  29. void redis_free()
  30. {
  31. if (c) {
  32. redisFree(c);
  33. }
  34. c = NULL;
  35. }
  36. int redis_save(const char *cmd)
  37. {
  38. int i = 0;
  39. redisReply *r = NULL;
  40. if (NULL == cmd) {
  41. return -1;
  42. }
  43. printf("%s\n", cmd);
  44. r = (redisReply *)redisCommand(c, cmd);
  45. if (NULL == r) {
  46. printf("Error[%d:%s]", c->err, c->errstr);
  47. return -1;
  48. }
  49. switch(r->type) {
  50. case REDIS_REPLY_STATUS:
  51. printf("type:%s, reply->len:%ld reply->str:%s\n", "REDIS_REPLY_STATUS", r->len, r->str);
  52. break;
  53. case REDIS_REPLY_ERROR:
  54. printf("type:%s, reply->len:%ld reply->str:%s\n", "REDIS_REPLY_ERROR", r->len, r->str);
  55. break;
  56. case REDIS_REPLY_INTEGER:
  57. printf("type:%s, reply->integer:%lld\n", "REDIS_REPLY_INTEGER", r->integer);
  58. break;
  59. case REDIS_REPLY_NIL:
  60. printf("type:%s, no data\n", "REDIS_REPLY_NIL");
  61. break;
  62. case REDIS_REPLY_STRING:
  63. printf("type:%s, reply->len:%ld reply->str:%s\n", "REDIS_REPLY_STRING", r->len, r->str);
  64. break;
  65. case REDIS_REPLY_ARRAY:
  66. printf("type:%s, reply->elements:%ld\n", "REDIS_REPLY_ARRAY", r->elements);
  67. for (i = 0; i < r->elements; i++) {
  68. printf("%d: %s\n", i, r->element[i]->str);
  69. }
  70. break;
  71. default:
  72. printf("unkonwn type:%d\n", r->type);
  73. break;
  74. }
  75. /*release reply and context */
  76. freeReplyObject(r);
  77. return 0;
  78. }
  79. QString redis_qstring(const char *cmd)
  80. {
  81. redisReply *r = NULL;
  82. if (NULL == cmd) {
  83. return "error";
  84. }
  85. printf("%s\n", cmd);
  86. r = (redisReply *)redisCommand(c, cmd);
  87. if (NULL == r) {
  88. printf("Error[%d:%s]", c->err, c->errstr);
  89. return "error";
  90. }
  91. QString data = r->str;
  92. /*release reply and context */
  93. freeReplyObject(r);
  94. return data;
  95. }
  96. #endif // REDIS_H