#ifndef REDIS_H #define REDIS_H #include #include #include #include #include #include #include #include #define REDIS_HOST "127.0.0.1" #define REDIS_PORT 6379 redisContext *c = NULL; int redisconnected; int redis_init() { c = redisConnect(REDIS_HOST, REDIS_PORT); if (NULL == c || c->err) { if(c) { printf("Redis [%s:%d], Error:[%s]\n", REDIS_HOST, REDIS_PORT, c->errstr); redisFree(c); } else { printf("Redis [%s:%d] failure\n", REDIS_HOST, REDIS_PORT); } return -1; } return 0; } void redis_free() { if (c) { redisFree(c); } c = NULL; } int redis_save(const char *cmd) { int i = 0; redisReply *r = NULL; if (NULL == cmd) { return -1; } printf("%s\n", cmd); r = (redisReply *)redisCommand(c, cmd); if (NULL == r) { printf("Error[%d:%s]", c->err, c->errstr); return -1; } switch(r->type) { case REDIS_REPLY_STATUS: printf("type:%s, reply->len:%ld reply->str:%s\n", "REDIS_REPLY_STATUS", r->len, r->str); break; case REDIS_REPLY_ERROR: printf("type:%s, reply->len:%ld reply->str:%s\n", "REDIS_REPLY_ERROR", r->len, r->str); break; case REDIS_REPLY_INTEGER: printf("type:%s, reply->integer:%lld\n", "REDIS_REPLY_INTEGER", r->integer); break; case REDIS_REPLY_NIL: printf("type:%s, no data\n", "REDIS_REPLY_NIL"); break; case REDIS_REPLY_STRING: printf("type:%s, reply->len:%ld reply->str:%s\n", "REDIS_REPLY_STRING", r->len, r->str); break; case REDIS_REPLY_ARRAY: printf("type:%s, reply->elements:%ld\n", "REDIS_REPLY_ARRAY", r->elements); for (i = 0; i < r->elements; i++) { printf("%d: %s\n", i, r->element[i]->str); } break; default: printf("unkonwn type:%d\n", r->type); break; } /*release reply and context */ freeReplyObject(r); return 0; } QString redis_qstring(const char *cmd) { redisReply *r = NULL; if (NULL == cmd) { return "error"; } printf("%s\n", cmd); r = (redisReply *)redisCommand(c, cmd); if (NULL == r) { printf("Error[%d:%s]", c->err, c->errstr); return "error"; } QString data = r->str; /*release reply and context */ freeReplyObject(r); return data; } #endif // REDIS_H