hiredis的封装类

对hiredis再次封装

cautoredisreply.h

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
#ifndef CAUTOREDISREPLY_H
#define CAUTOREDISREPLY_H


#include "hiredis.h"
#include <stdlib.h>
#include <string>
#include <stdio.h>
#include <strings.h>
#include <assert.h>
#include <vector>
#include <stdint.h>
#include <sstream>
#include <set>

using namespace std;

enum enRedisResult
{
REDIS_SUCCESS, // 成功
REDIS_FAILED, // 失败
};

// 用结构体包装一下,避免使用者忘记回收reply
class CAutoRedisReply
{
public:
CAutoRedisReply(redisReply* r = NULL);
~CAutoRedisReply();
public:
void set(redisReply* r);
redisReply* get();
private:
redisReply* m_r;
};

class CRedisClient
{
public:
CRedisClient() : m_bConnected(false), m_redisCtx(NULL)
{
}

virtual ~CRedisClient()
{
clear();
}
public:
// 初始化
bool Init(string IP, int port, string password, int timeout=5000);
public:
// 判断指定key是否存在
bool Exist(string key);

// 设置指定key的值,过期时间单位:秒
int Set(string key, string val, uint32_t expire);

// 获取指定key的值,字符串类型
string Get(string key);

// 设置指定key的值,bin类型
// pVal : 内存地址
// len : 内存大小
// expire : 过期时间,单位:秒
int Set(string key, const char* pVal, int length, uint32_t expire);

// 获取指定key的值,bin类型
int Get(string key, CAutoRedisReply& reply);
// 设置过期时间,不对外提供的原因是强制要求set key的同时必须设置过期时间
int expireKey(string key, uint32_t expire);
private:
// 连接
bool connect();

void clear();

// 设置过期时间,不对外提供的原因是强制要求set key的同时必须设置过期时间
// int expireKey(string key, uint32_t expire);
private:
bool m_bConnected;// 是否已连接成功
redisContext* m_redisCtx; // redisl连接
string m_szIp; // redis服务器IP
int m_nPort; // redis服务器端口
string m_password; // redis密码
uint32_t m_timeout; // 超时时间,单位:毫秒
};


#endif // CAUTOREDISREPLY_H

cautoredisreply.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
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#include "cautoredisreply.h"
#include <string.h>

using namespace std;

CAutoRedisReply::CAutoRedisReply(redisReply* r): m_r(r)
{
}

CAutoRedisReply::~CAutoRedisReply()
{
if (m_r != nullptr) //由NULL替换为nullptr
{
freeReplyObject(m_r);
}
}

void CAutoRedisReply::set(redisReply* r)
{
if (m_r != nullptr) //由NULL替换为nullptr
{
freeReplyObject(m_r);
}

m_r = r;
}

redisReply* CAutoRedisReply::get()
{
return m_r;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// 初始化
bool CRedisClient::Init(string IP, int port, string password, int timeout/*=5000*/)
{
if (IP=="" || port<=0 || password == "")
{
printf("CRedisClient::Init(), IP=="" || port<=0 || password == "", IP=%s, prot=%d, password=%s",IP.c_str(), port,password.c_str());
return false;
}

m_szIp = IP;
m_nPort = port;
m_password = password;
m_timeout = timeout;

return connect();
}

// 判断指定key是否存在
bool CRedisClient::Exist(string key)
{
bool bSuc = connect();
if (!bSuc)
{
printf("CRedisClient::Exist(), connect failed");
return false;
}

ostringstream os;
os<< "exists " << key;

CAutoRedisReply autoR;
redisReply* r = (redisReply*)redisCommand(m_redisCtx, os.str().c_str());
if (NULL == r)
{
printf("CRedisClient::Exist(), call redisCommand() printf, redis break connection,m_redisCtx: %p", m_redisCtx);
m_bConnected = false;
return false;
}
autoR.set(r);

// 类型检测
if (r->type != REDIS_REPLY_INTEGER)
{
printf("CRedisClient::Exist(), result printf, r->type=%d", r->type);
return false;
}

return (r->integer==1);
}

// 设置指定key的值,过期时间单位:秒
int CRedisClient::Set(string key, string val, uint32_t expire)
{
bool bSuc = connect();
if (!bSuc)
{
printf("CRedisClient::Set(), connect failed");
return REDIS_FAILED;
}

ostringstream os;
os<< "set " << key <<" "<< val;

// set命令
CAutoRedisReply autoR;
redisReply* r = (redisReply*)redisCommand(m_redisCtx, os.str().c_str());
if (NULL == r)
{
printf("CRedisClient::Set(),call redisCommand() printf,command=%s, redis break connection,m_redisCtx: %p",os.str().c_str(), m_redisCtx);
m_bConnected = false;
return REDIS_FAILED;
}
autoR.set(r);

if (r->type!=REDIS_REPLY_STATUS || r->str==NULL || strcasecmp(r->str, "OK") != 0)
{
printf("CRedisClient::Set(),result printf, type=%d, command=%s, errmsg=%s", r->type, os.str().c_str(), r->str);
return REDIS_FAILED;
}

// expire命令
return expireKey(key, expire);
}
///@ 带健值读取
string CRedisClient::Get(string key)
{
bool bSuc = connect();
if (!bSuc)
{
printf("CRedisClient::Get(), connect failed");
return "";
}

ostringstream os;
os<< "get " << key;

CAutoRedisReply autoR;
redisReply* r = (redisReply*)redisCommand(m_redisCtx, os.str().c_str());
if (NULL == r)
{
printf("CRedisClient::Get(), call redisCommand printf, redis break connection,m_redisCtx: %p", m_redisCtx);
m_bConnected = false;
return "";
}
autoR.set(r);

// 类型检测
if (r->type != REDIS_REPLY_STRING || r->str==NULL || r->len==0)
{
printf("CRedisClient::Get(),result printf, type=%d, str=%s, len=%lu",r->type, r->str, r->len);
return "";
}

return string(r->str);
}

// 设置指定key的值,bin类型
// pVal : 内存地址
// len : 内存大小
// expire : 过期时间,单位:秒
int CRedisClient::Set(string key, const char* pVal, int length, uint32_t expire)
{
bool bSuc = connect();
if (!bSuc)
{
printf("CRedisClient::Set(), connect failed");
return REDIS_FAILED;
}

const char* cmd[5];
size_t len[5];
cmd[0] = "SET";
len[0] = strlen(cmd[0]);
cmd[1] = key.c_str();
len[1] = strlen(cmd[1]);
cmd[2] = pVal;
len[2] = length;

// set命令
CAutoRedisReply autoR;
redisReply* r = (redisReply *)redisCommandArgv(m_redisCtx, 3, &cmd[0], &len[0]);
if (r == NULL)
{
printf("CRedisClient::Set(),call redisCommandArgv() printf, redis break connection,m_redisCtx: %p", m_redisCtx);
return REDIS_FAILED;
}
autoR.set(r);

if (r->type!=REDIS_REPLY_STATUS || r->str==NULL || strcasecmp(r->str, "OK") != 0)
{
printf("CRedisClient::Set(),result printf, type=%d, errmsg=%s", r->type, r->str);
return REDIS_FAILED;
}

// expire命令
return expireKey(key, expire);
}

// 获取指定key的值,bin类型
int CRedisClient::Get(string key, CAutoRedisReply& reply)
{
bool bSuc = connect();
if (!bSuc)
{
printf("CRedisClient::Get(), connect failed");
return REDIS_FAILED;
}

const char* cmd[3];
size_t len[3];
cmd[0] = "GET";
len[0] = strlen(cmd[0]);
cmd[1] = key.c_str();
len[1] = strlen(cmd[1]);

// set命令
redisReply* r = (redisReply *)redisCommandArgv(m_redisCtx, 2, &cmd[0], &len[0]);
if (r == NULL)
{
printf("CRedisClient::Get(),call redisCommandArgv() printf, redis break connection,m_redisCtx: %p", m_redisCtx);
return REDIS_FAILED;
}

if (r->type!=REDIS_REPLY_STRING)
{
printf("CRedisClient::Get(),result printf, type=%d, errmsg=%s", r->type, r->str);
freeReplyObject(r);
return REDIS_FAILED;
}
reply.set(r);

return REDIS_SUCCESS;
}

// 设置过期时间
int CRedisClient::expireKey(string key, uint32_t expire)
{
bool bSuc = connect();
if (!bSuc)
{
printf("CRedisClient::expireKey(), connect failed");
return REDIS_FAILED;
}

ostringstream os;
os<< "expire " << key <<" "<< expire;

CAutoRedisReply autoR;
redisReply* r = (redisReply*)redisCommand(m_redisCtx, os.str().c_str());
if (NULL == r)
{
printf("CRedisClient::expireKey(),call redisCommand() printf,command=%s, redis break connection,m_redisCtx: %p",os.str().c_str(), m_redisCtx);
m_bConnected = false;
return REDIS_FAILED;
}
autoR.set(r);

if (r->type!=REDIS_REPLY_INTEGER || r->integer != 1)
{
printf("CRedisClient::expireKey(),result printf, type=%d, command=%s, errmsg=%s", r->type, os.str().c_str(), r->str);
return REDIS_FAILED;
}

return REDIS_SUCCESS;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void CRedisClient::clear()
{
if (m_redisCtx != NULL)
{
redisFree(m_redisCtx);
m_redisCtx = NULL;
}
}

// 连接
bool CRedisClient::connect()
{
if (m_bConnected)
{
return true;
}

clear();

struct timeval tv;
tv.tv_sec = m_timeout/1000;
tv.tv_usec = m_timeout%1000;

// 连接
m_redisCtx = redisConnectWithTimeout(m_szIp.c_str(), m_nPort, tv);
if (NULL==m_redisCtx || m_redisCtx->err!=0)
{
printf("CRedisClient::connect(), connect redis server failed, ip:%s, port:%d, password=%s, err:%d, errmsg:%s",m_szIp.c_str(), m_nPort, m_password.c_str(), m_redisCtx->err, m_redisCtx->errstr);
clear();
return false;
}

// 认证
redisReply* pReply = (redisReply*)redisCommand(m_redisCtx, "auth %s", m_password.c_str());
if (pReply->type == REDIS_REPLY_ERROR)
{
printf("CRedisClient::connect(), auth redis server failed, ip:%s, port:%d, password=%s, errmsg:%s", m_szIp.c_str(), m_nPort, m_password.c_str(), pReply->str);
freeReplyObject(pReply);
clear();
return false;
}
freeReplyObject(pReply);

m_bConnected = true;

// 设置超时时间
redisSetTimeout(m_redisCtx, tv);

return true;
}

使用实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 子线程redis连接实例(新版)
CRedisClient m_redisClient;

// redis配置,应该写在配置文件中读取,这里只是简单演示
string IP = m_recvdipaddr.toStdString();
int port = 6379;
string password = "yyjtest";
int timeout = 5000;
// 初始化,并建立连接
if(!m_redisClient.Init(IP,port,password,timeout))
{
qDebug()<<"子线程打开redis失败";
}
else{
int result1 = m_redisClient.Set("verification_code:"+m_recvdusername.toStdString(),m_recvdcode.toStdString(), rftime);
int result2 =m_redisClient.expireKey("login_tokens_client:"+m_recvdusername.toStdString(),rftime);
qDebug()<<"子线程刷新redis成功";
}

hiredis的封装类
https://macbook-pro-gala.github.io/2023/04/29/hiredis的封装类/
作者
lyh
发布于
2023年4月29日
许可协议