-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredis.c
More file actions
139 lines (106 loc) · 2.26 KB
/
redis.c
File metadata and controls
139 lines (106 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include "util.h"
#include "redis.h"
/**
*/
redisContext * rdsConnect(char * server, int port) {
redisContext *c;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = redisConnectWithTimeout(server, port, timeout);
if(c == NULL) {
printf("DEBUG: Unable to connect to redis (%s:%d).\n", server, port);
return NULL;
}
if(c->err) {
if(DEBUG) {
printf("DEBUG: Unable to connect to redis (%s:%d). Got error: %d\n", server, port, c->err);
}
redisFree(c);
return NULL;
}
return c;
}
/**
*/
unsigned int rdsExists(redisContext *rc, char * key) {
unsigned int ret;
redisReply *reply;
if(rc == NULL) {
return REDIS_CONNECTION_FAIL;
}
reply = redisCommand(rc, "EXISTS %s", key);
ret = reply->integer == 1 ? STATUS_SUCCESS : STATUS_FAILURE;
freeReplyObject(reply);
return ret;
}
/**
*/
unsigned int rdsStore(redisContext *rc,
char * key,
char * data,
unsigned int expire) {
unsigned int ret;
redisReply *reply;
if(rc == NULL) {
return REDIS_CONNECTION_FAIL;
}
if(expire == 0) {
// SET mykey "myval"
reply = redisCommand(rc, "SET %s %s", key, data);
}
else {
// SETEX mykey 10 "myval"
reply = redisCommand(rc, "SETEX %s %d %s", key, expire, data);
}
ret = strcasecmp(reply->str, "OK") == 0 ? STATUS_SUCCESS : STATUS_FAILURE;
freeReplyObject(reply);
return ret;
}
/**
*/
unsigned int rdsFetch(redisContext *rc, char * key, char ** data) {
redisReply *reply;
if(rc == NULL) {
return REDIS_CONNECTION_FAIL;
}
reply = redisCommand(rc, "GET %s", key);
if(reply->str == NULL || strcmp(reply->str,"") == 0) {
return STATUS_FAILURE;
}
(*data) = strdup(reply->str);
freeReplyObject(reply);
return STATUS_SUCCESS;
}
/**
*/
unsigned int rdsDelete(redisContext *rc, char * key) {
unsigned int ret;
redisReply *reply;
if(rc == NULL) {
return REDIS_CONNECTION_FAIL;
}
reply = redisCommand(rc, "DEL %s", key);
ret = reply->integer == 1 ? STATUS_SUCCESS : STATUS_FAILURE;
freeReplyObject(reply);
return ret;
}
/**
*/
void rdsDisconnect(redisContext *rc) {
if(rc == NULL) {
return;
}
redisFree(rc);
}
/**
*/
/**
*/
void rdsFlush(redisContext *rc) {
unsigned int ret;
redisReply *reply;
if(rc == NULL) {
return;
}
reply = redisCommand(rc, "FLUSHALL");
freeReplyObject(reply);
}