Skip to content

Commit 13ecea4

Browse files
committed
auto expand & shrink wbuf in RedisConn
1 parent 7255a77 commit 13ecea4

File tree

3 files changed

+20
-8
lines changed

3 files changed

+20
-8
lines changed

pink/include/pink_define.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ enum RetCode {
7676
* define the redis protocol
7777
*/
7878
#define REDIS_MAX_MESSAGE 67108864 // 64MB
79+
#define DEFAULT_WBUF_SIZE 262144 // 256KB
7980
#define REDIS_IOBUF_LEN 16384
8081
#define REDIS_REQ_INLINE 1
8182
#define REDIS_REQ_MULTIBULK 2

pink/include/redis_conn.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class RedisConn: public PinkConn {
2525
virtual ~RedisConn();
2626
void ResetClient();
2727

28-
bool ExpandWbuf();
28+
bool ExpandWbufTo(uint32_t new_size);
2929
uint32_t wbuf_size_;
3030

3131
virtual ReadStatus GetRequest();

pink/src/redis_conn.cc

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ RedisConn::RedisConn(const int fd,
133133
const std::string &ip_port,
134134
ServerThread *thread)
135135
: PinkConn(fd, ip_port, thread),
136-
wbuf_size_(REDIS_MAX_MESSAGE),
136+
wbuf_size_(DEFAULT_WBUF_SIZE),
137137
wbuf_len_(0),
138138
last_read_pos_(-1),
139139
next_parse_pos_(0),
@@ -144,7 +144,7 @@ RedisConn::RedisConn(const int fd,
144144
is_overtake_(false),
145145
wbuf_pos_(0) {
146146
rbuf_ = reinterpret_cast<char*>(malloc(sizeof(char) * REDIS_MAX_MESSAGE));
147-
wbuf_ = reinterpret_cast<char*>(malloc(sizeof(char) * REDIS_MAX_MESSAGE));
147+
wbuf_ = reinterpret_cast<char*>(malloc(sizeof(char) * DEFAULT_WBUF_SIZE));
148148
}
149149

150150
RedisConn::~RedisConn() {
@@ -282,14 +282,19 @@ void RedisConn::ResetClient() {
282282
bulk_len_ = -1;
283283
}
284284

285-
bool RedisConn::ExpandWbuf() {
286-
if (wbuf_size_ >= (uint32_t)(REDIS_MAX_MESSAGE * (uint32_t)32)) {
285+
bool RedisConn::ExpandWbufTo(uint32_t new_size) {
286+
if (new_size <= wbuf_size_) {
287+
return true;
288+
}
289+
void* new_wbuf = realloc(wbuf_, new_size);
290+
if (new_wbuf != nullptr) {
291+
wbuf_ = reinterpret_cast<char*>(new_wbuf);
292+
wbuf_size_ = new_size;
293+
return true;
294+
} else {
287295
wbuf_pos_ = 0;
288296
return false;
289297
}
290-
wbuf_size_ *= 2;
291-
wbuf_ = reinterpret_cast<char*>(realloc(wbuf_, wbuf_size_));
292-
return true;
293298
}
294299

295300
ReadStatus RedisConn::ProcessInputBuffer() {
@@ -379,6 +384,12 @@ WriteStatus RedisConn::SendReply() {
379384
if (wbuf_pos_ == wbuf_len_) {
380385
wbuf_len_ = 0;
381386
wbuf_pos_ = 0;
387+
if (wbuf_size_ > DEFAULT_WBUF_SIZE) {
388+
free(wbuf_);
389+
wbuf_ = reinterpret_cast<char*>(malloc(sizeof(char) *
390+
DEFAULT_WBUF_SIZE));
391+
wbuf_size_ = DEFAULT_WBUF_SIZE;
392+
}
382393
}
383394
}
384395
if (nwritten == -1) {

0 commit comments

Comments
 (0)