1 #include "redis_client.h"
2 #include "test_core.h"
3
4 #include <memory>
5
6 using namespace std;
7
8 namespace swoole {
Connect(const string & host,int port,struct timeval timeout)9 bool RedisClient::Connect(const string &host, int port, struct timeval timeout) {
10 redisContext *c = redisConnectWithTimeout(host.c_str(), port, timeout);
11 if (c == NULL) {
12 printf("Connection error: can't allocate redis context\n");
13 return false;
14 }
15
16 if (c->err) {
17 printf("Connection error: %s\n", c->errstr);
18 redisFree(c);
19 return false;
20 }
21
22 ctx = c;
23 return true;
24 }
25
Get(const string & key)26 string RedisClient::Get(const string &key) {
27 const char *argv[] = {"GET", key.c_str()};
28 size_t argvlen[] = {strlen(argv[0]), key.length()};
29
30 auto reply = Request(SW_ARRAY_SIZE(argv), argv, argvlen);
31 if (!reply.empty() && reply->str) {
32 return string(reply->str, reply->len);
33 } else {
34 return "";
35 }
36 }
37
Set(const string & key,const string & value)38 bool RedisClient::Set(const string &key, const string &value) {
39 const char *argv[] = {"SET", key.c_str(), value.c_str()};
40 size_t argvlen[] = {strlen(argv[0]), key.length(), value.length()};
41
42 auto reply = Request(SW_ARRAY_SIZE(argv), argv, argvlen);
43 if (!reply.empty() && reply->type == REDIS_REPLY_STATUS && strncmp(reply->str, "OK", 2) == 0) {
44 return true;
45 } else {
46 return false;
47 }
48 }
49
Request(int argc,const char ** argv,const size_t * argvlen)50 RedisReply RedisClient::Request(int argc, const char **argv, const size_t *argvlen) {
51 return redisCommandArgv(ctx, argc, argv, argvlen);
52 }
53
Request(const vector<string> & args)54 RedisReply RedisClient::Request(const vector<string> &args) {
55 ctx->err = 0;
56
57 size_t n = args.size();
58 const char **argv = new const char *[n];
59 size_t *argvlen = new size_t[n];
60
61 for (size_t i = 0; i < args.size(); i++) {
62 argv[i] = args[i].c_str();
63 argvlen[i] = args[i].length();
64 }
65
66 auto reply = Request(args.size(), (const char **) argv, (const size_t *) argvlen);
67
68 delete[] argv;
69 delete[] argvlen;
70
71 return reply;
72 }
73
74 } // namespace swoole
75