forked from sonic-net/sonic-swss-common
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredispipeline.h
More file actions
107 lines (91 loc) · 2.38 KB
/
Copy pathredispipeline.h
File metadata and controls
107 lines (91 loc) · 2.38 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
#pragma once
#include <string>
#include <functional>
#include "redisreply.h"
#include "rediscommand.h"
#include "dbconnector.h"
namespace swss {
class RedisPipeline {
public:
const size_t COMMAND_MAX;
static constexpr int NEWCONNECTOR_TIMEOUT = 0;
RedisPipeline(DBConnector *db, size_t sz = 128)
: COMMAND_MAX(sz)
, m_remaining(0)
{
m_db = db->newConnector(NEWCONNECTOR_TIMEOUT);
}
~RedisPipeline() {
flush();
delete m_db;
}
redisReply *push(const RedisCommand& command, int expectedType)
{
switch (expectedType)
{
case REDIS_REPLY_NIL:
case REDIS_REPLY_STATUS:
case REDIS_REPLY_INTEGER:
{
redisAppendFormattedCommand(m_db->getContext(), command.c_str(), command.length());
m_expectedTypes.push(expectedType);
m_remaining++;
mayflush();
return NULL;
}
default:
{
flush();
RedisReply r(m_db, command, expectedType);
return r.release();
}
}
}
std::string loadRedisScript(const std::string& script)
{
RedisCommand loadcmd;
loadcmd.format("SCRIPT LOAD %s", script.c_str());
RedisReply r = push(loadcmd, REDIS_REPLY_STRING);
std::string sha = r.getReply<std::string>();
return sha;
}
// The caller is responsible to release the reply object
redisReply *pop()
{
if (m_remaining == 0) return NULL;
redisReply *reply;
redisGetReply(m_db->getContext(), (void**)&reply);
RedisReply r(reply);
m_remaining--;
int expectedType = m_expectedTypes.front();
m_expectedTypes.pop();
r.checkReplyType(expectedType);
if (expectedType == REDIS_REPLY_STATUS)
{
r.checkStatusOK();
}
return r.release();
}
void flush()
{
while(m_remaining)
{
// Construct an object to use its dtor, so that resource is released
RedisReply r(pop());
}
}
size_t size()
{
return m_remaining;
}
private:
DBConnector *m_db;
std::queue<int> m_expectedTypes;
size_t m_remaining;
void mayflush()
{
if (m_remaining >= COMMAND_MAX)
flush();
}
};
}