0

在 redisAsyncContext 中,stuct ev 被定义为:

struct {  
    void *data;  
    void (*addRead)(void *privdata);  
    void (*delRead)(void *privdata);  
    void (*addWrite)(void *privdata);  
    void (*delWrite)(void *privdata);  
    void (*cleanup)(void *privdata);  
} ev;  

有一个功能:

void CleanUpEvent()
{
    if (m_pstContext->ev.delRead)
    {
        m_pstContext->ev.delRead(m_pstContext->ev.data);
    }

    if (m_pstContext->ev.delWrite)
    {
        m_pstContext->ev.delWrite(m_pstContext->ev.data);
    }
}

这个怎么运作?我什么时候应该使用ev?

4

1 回答 1

0

基本上你只需要提供连接和断开回调,hiredis 会单独为你做其余的事情。

#include <hiredis.h>
#include <async.h>
#include <adapters/libuv.h>

void connectCallback(const redisAsyncContext *c, int status);
void disconnectCallback(const redisAsyncContext *c, int status);
void getCallback(redisAsyncContext *c, void *r, void *privdata);

int main (int argc, char **argv) {

    //make a async context
    redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
    if (c->err) {
        /* Let *c leak for now... */
        printf("Error: %s\n", c->errstr);
        return 1;
    }

    //now, you need to attach hiredis to your event loop, its depends on event lib that you are using
    //example for libuv
    redisLibuvAttach(c, uv_default_loop());

    //now we setup callbacks
    redisAsyncSetConnectCallback(c, connectCallback);
    redisAsyncSetDisconnectCallback(c, disconnectCallback);

    //enquee "SET foo bar" without callback
    redisAsyncCommand(c, NULL, NULL, "SET foo %b", "bar", strlen("bar"));

    //enquee "GET foo" with callback and privdata "end-1"
    redisAsyncCommand(c, getCallback, (char*)"end-1", "GET foo");

    //run your event loop
    uv_run(loop, UV_RUN_DEFAULT);

    return 0;
}

void connectCallback(const redisAsyncContext *c, int status) {
    if (status != REDIS_OK) {
        printf("Error: %s\n", c->errstr);
        return;
    }
    printf("Connected...\n");
}

void disconnectCallback(const redisAsyncContext *c, int status) {
    if (status != REDIS_OK) {
        printf("Error: %s\n", c->errstr);
        return;
    }
    printf("Disconnected...\n");
}

void getCallback(redisAsyncContext *c, void *r, void *privdata) {
    redisReply *reply = r;
    if (reply == NULL) return;
    printf("argv[%s]: %s\n", (char*)privdata, reply->str);

    /* Disconnect after receiving the reply to GET */
    redisAsyncDisconnect(c);
}

检查https://github.com/redis/hiredis/tree/master/examples以获取有关不同事件库的更多示例。

于 2017-07-30T08:08:13.900 回答