文先生的博客 求职,坐标深圳。(wenfh2020@126.com)

hiredis + libev 异步测试

2018-06-17

hiredis 测试写命令 set key value,几个字节的 value,轻松 10 万+ 并发;

1024 个字节的 value,10w 请求需要耗时 1.5 秒左右。

所以 hiredis 的异步使用性能非常给力的,而且程序的性能损耗也不高。

只是异步使用有点反人类,业务都要在 callback 里面处理,没有同步调用那么直观。


1. 测试

hiredis 代码提供了 libev 的 I/O 回调。只要绑定相关 libev 的相关回调,即可使用,代码也相对比较精简。(测试源码)

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
void RdsCbConnect(const redisAsyncContext* pRdsContext, int iStatus);
void RdsCbDisConnect(const redisAsyncContext* pRdsContext, int iStatus);
void RdsCbCmd(redisAsyncContext* pRdsContext, void* pReply, void* pData);

void RdsCbCmd(redisAsyncContext* pRdsContext, void* pReply, void* pData) {
    if (NULL == pReply) {
        printf("call back repplay null!\n");
        return;
    }

    redisReply* pRdsReply = (redisReply*)pReply;
    if (REDIS_REPLY_NIL == pRdsReply->type) {
        printf("reply nil\n");
        return;
    }

    /* printf("%d, redis reply info: type = %d, string = %s\n",
           ++g_iCmdCallback, pRdsReply->type, pRdsReply->str); */

    if (++g_iCmdCallback >= TEST_CMD_COUNT) {
        unsigned long long ullEndTime = GetMicrosecond();
        printf("test end time: %s, %llu, interval: %llu\n",
               GetCurrentTime().c_str(), ullEndTime,
               ullEndTime - g_ullBeginTime);
        redisAsyncDisconnect((redisAsyncContext*)pRdsContext);
    }
}

int main() {
    redisAsyncContext* pRdsContext = redisAsyncConnect(IP, PORT);
    if (pRdsContext->err != REDIS_OK) {
        printf("async redis connect failed! err code = %d, err msg = %s\n",
               pRdsContext->err, pRdsContext->errstr);
        return 1;
    }

    struct ev_loop* pLoop = EV_DEFAULT;
    redisLibevAttach(pLoop, pRdsContext);
    redisAsyncSetConnectCallback(pRdsContext, RdsCbConnect);
    redisAsyncSetDisconnectCallback(pRdsContext, RdsCbDisConnect);
    ev_run(pLoop, 0);
    return 0;
}

测试结果(interval 是微妙为单位的时间差)

1
2
3
4
5
connect call back, status = 0
test write cmd count = 100000
test begin time: 2018-06-17 08:17:43, 1529194663712890
test end time: 2018-06-17 08:17:44, 1529194664952655, interval: 1239765  
disconnect call back, status = 0

作者公众号
微信公众号,干货持续更新~