redisx.cpp
7.25 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/**
* Redis C++11 wrapper.
*/
#include <signal.h>
//#include <event2/thread.h>
#include "redisx.hpp"
using namespace std;
namespace redisx {
// Global mutex to manage waiting for connected state
mutex connected_lock;
// Map of ev_timer events to pointers to Command objects
// Used to get the object back from the timer watcher callback
unordered_map<ev_timer*, void*> timer_callbacks;
void connected(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
cerr << "[ERROR] Connecting to Redis: " << c->errstr << endl;
return;
}
cout << "Connected to Redis." << endl;
connected_lock.unlock();
}
void disconnected(const redisAsyncContext *c, int status) {
if (status != REDIS_OK) {
cerr << "[ERROR] Disconnecting from Redis: " << c->errstr << endl;
return;
}
cout << "Disconnected from Redis." << endl;
connected_lock.lock();
}
Redis::Redis(const string& host, const int port)
: host(host), port(port), cmd_count(0), to_exit(false) {
lock_guard<mutex> lg(queue_guard);
connected_lock.lock();
signal(SIGPIPE, SIG_IGN);
c = redisAsyncConnect(host.c_str(), port);
if (c->err) {
printf("Error: %s\n", c->errstr);
return;
}
redisLibevAttach(EV_DEFAULT_ c);
redisAsyncSetConnectCallback(c, connected);
redisAsyncSetDisconnectCallback(c, disconnected);
}
Redis::~Redis() {
redisAsyncDisconnect(c);
stop();
}
void Redis::run_blocking() {
// Events to connect to Redis
ev_run(EV_DEFAULT_ EVRUN_NOWAIT);
lock_guard<mutex> lg(connected_lock);
// Continuously create events and handle them
while (!to_exit) {
process_queued_commands();
ev_run(EV_DEFAULT_ EVRUN_NOWAIT);
}
// Handle exit events
ev_run(EV_DEFAULT_ EVRUN_NOWAIT);
// Let go for block_until_stopped method
unique_lock<mutex> ul(exit_waiter_lock);
exit_waiter.notify_one();
}
void Redis::run() {
event_loop_thread = thread([this] { run_blocking(); });
event_loop_thread.detach();
}
void Redis::stop() {
to_exit = true;
}
void Redis::block_until_stopped() {
unique_lock<mutex> ul(exit_waiter_lock);
exit_waiter.wait(ul, [this]() { return to_exit.load(); });
}
/**
* Submit an asynchronous command to the Redis server. Return
* true if succeeded, false otherwise.
*/
template<class ReplyT>
bool submit_to_server(Command<ReplyT>* cmd_obj) {
if (redisAsyncCommand(cmd_obj->c, command_callback<ReplyT>, (void*)cmd_obj, cmd_obj->cmd.c_str()) != REDIS_OK) {
cerr << "[ERROR] Async command \"" << cmd_obj->cmd << "\": " << cmd_obj->c->errstr << endl;
cmd_obj->free_if_done();
return false;
}
return true;
}
template<class ReplyT>
void submit_command_callback(struct ev_loop* loop, ev_timer* timer, int revents) {
auto cmd_obj = (Command<ReplyT>*)timer_callbacks.at(timer);
submit_to_server<ReplyT>(cmd_obj);
}
template<class ReplyT>
bool Redis::process_queued_command(void* cmd_ptr) {
auto& command_map = get_command_map<ReplyT>();
auto it = command_map.find(cmd_ptr);
if(it == command_map.end()) return false;
Command<ReplyT>* cmd_obj = it->second;
command_map.erase(cmd_ptr);
if((cmd_obj->repeat == 0) && (cmd_obj->after == 0)) {
submit_to_server<ReplyT>(cmd_obj);
} else {
cmd_obj->timer = new ev_timer();
timer_callbacks[cmd_obj->timer] = (void*)cmd_obj;
ev_timer_init(cmd_obj->timer, submit_command_callback<ReplyT>, cmd_obj->after, cmd_obj->repeat);
ev_timer_start(EV_DEFAULT_ cmd_obj->timer);
cmd_obj->timer_guard.unlock();
}
return true;
}
void Redis::process_queued_commands() {
lock_guard<mutex> lg(queue_guard);
while(!command_queue.empty()) {
void* cmd_ptr = command_queue.front();
if(process_queued_command<const redisReply*>(cmd_ptr)) {}
else if(process_queued_command<const string&>(cmd_ptr)) {}
else if(process_queued_command<const char*>(cmd_ptr)) {}
else if(process_queued_command<int>(cmd_ptr)) {}
else if(process_queued_command<long long int>(cmd_ptr)) {}
else throw runtime_error("[FATAL] Command pointer not found in any queue!");
command_queue.pop();
cmd_count++;
}
}
long Redis::num_commands_processed() {
lock_guard<mutex> lg(queue_guard);
return cmd_count;
}
// ----------------------------
template<> unordered_map<void*, Command<const redisReply*>*>& Redis::get_command_map() { return commands_redis_reply; }
template<>
void invoke_callback(Command<const redisReply*>* cmd_obj, redisReply* reply) {
cmd_obj->invoke(reply);
}
template<> unordered_map<void*, Command<const string&>*>& Redis::get_command_map() { return commands_string_r; }
template<>
void invoke_callback(Command<const string&>* cmd_obj, redisReply* reply) {
if(reply->type != REDIS_REPLY_STRING && reply->type != REDIS_REPLY_STATUS) {
cerr << "[ERROR] " << cmd_obj->cmd << ": Received non-string reply." << endl;
return;
}
cmd_obj->invoke(reply->str);
}
template<> unordered_map<void*, Command<const char*>*>& Redis::get_command_map() { return commands_char_p; }
template<>
void invoke_callback(Command<const char*>* cmd_obj, redisReply* reply) {
if(reply->type != REDIS_REPLY_STRING && reply->type != REDIS_REPLY_STATUS) {
cerr << "[ERROR] " << cmd_obj->cmd << ": Received non-string reply." << endl;
return;
}
cmd_obj->invoke(reply->str);
}
template<> unordered_map<void*, Command<int>*>& Redis::get_command_map() { return commands_int; }
template<>
void invoke_callback(Command<int>* cmd_obj, redisReply* reply) {
if(reply->type != REDIS_REPLY_INTEGER) {
cerr << "[ERROR] " << cmd_obj->cmd << ": Received non-integer reply." << endl;
return;
}
cmd_obj->invoke((int)reply->integer);
}
template<> unordered_map<void*, Command<long long int>*>& Redis::get_command_map() { return commands_long_long_int; }
template<>
void invoke_callback(Command<long long int>* cmd_obj, redisReply* reply) {
if(reply->type != REDIS_REPLY_INTEGER) {
cerr << "[ERROR] " << cmd_obj->cmd << ": Received non-integer reply." << endl;
return;
}
cmd_obj->invoke(reply->integer);
}
// ----------------------------
// Helpers
// ----------------------------
void Redis::command(const char* cmd) {
command<const redisReply*>(cmd, NULL);
}
//void Redis::get(const char* key, function<void(const string&, const char*)> callback) {
// string cmd = string("GET ") + key;
// command<const char*>(cmd.c_str(), callback);
//}
//
//void Redis::set(const char* key, const char* value) {
// string cmd = string("SET ") + key + " " + value;
// command<const char*>(cmd.c_str(), [](const string& command, const char* reply) {
// if(strcmp(reply, "OK"))
// cerr << "[ERROR] " << command << ": SET failed with reply " << reply << endl;
// });
//}
//
//void Redis::set(const char* key, const char* value, function<void(const string&, const char*)> callback) {
// string cmd = string("SET ") + key + " " + value;
// command<const char*>(cmd.c_str(), callback);
//}
//
//void Redis::del(const char* key) {
// string cmd = string("DEL ") + key;
// command<long long int>(cmd.c_str(), [](const string& command, long long int num_deleted) {
// if(num_deleted != 1)
// cerr << "[ERROR] " << command << ": Deleted " << num_deleted << " keys." << endl;
// });
//}
//
//void Redis::del(const char* key, function<void(const string&, long long int)> callback) {
// string cmd = string("DEL ") + key;
// command<long long int>(cmd.c_str(), callback);
//}
} // End namespace redis