-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.cpp
58 lines (42 loc) · 1.29 KB
/
redis.cpp
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
#include "redis.hpp"
// Constructor
Redis::Redis(string hostname, int port) {
// Connect to Redis server
this->connection = redisConnect(hostname.c_str(), port);
}
// Destructor
Redis::~Redis() {
// Free Redis connection
redisFree(this->connection);
}
bool Redis::alive() {
// Check if connection is alive
if (this->connection == NULL || this->connection->err) {
cerr << "Error: Connection to Redis server failed." << endl;
return false;
}
return true;
// End of function
}
bool Redis::setData(string key, string value) {
redisReply *reply = (redisReply *)redisCommand(this->connection, "SET %s %s", key.c_str(), value.c_str());
if (!reply) {
cerr << "Error: Failed to set key '" << key << "'." << endl;
return false;
}
freeReplyObject(reply);
// End of function
return true;
}
string Redis::getData(string key) {
redisReply *reply = (redisReply *)redisCommand(this->connection, "GET %s", key.c_str());
if (!reply || reply->type == REDIS_REPLY_NIL) {
cerr << "Error: Key '" << key << "' not found." << endl;
if (reply)
freeReplyObject(reply);
}
string value = reply->str;
freeReplyObject(reply);
return value;
// End of function
}