hiredis操作redis的函数API说明(未完待续)

一、同步函数接口

1.1 redisContext *redisConnect(const char *ip, int port)

  • 函数说明:

该函数用来连接redis数据库,参数为数据库的ip地址和端口,一般redis数据库的端口为6379

  • 返回指

该函数返回一个结构体redisContext。

  • 代码
    // 连接Redis服务
    redisContext *context = redisConnect("127.0.0.1", 6379);
    if (context == NULL || context->err) {
        if (context) {
            printf("%s\n", context->errstr);
        } else {
            printf("redisConnect error\n");
        }
        exit(EXIT_FAILURE);
    }
    printf("-----------------connect success--------------------\n");

1.2 void* redisCommand(redisContext *c, const char *format, …);

  • 函数说明

该函数执行命令,就如sql数据库中的SQL语句一样,只是执行的是redis数据库中的操作命令,第一个参数为连接数据库时返回的redisContext,剩下的参数为变参,就如C标准函数printf函数一样的变参。

  • 返回值

返回void*的指针,实际为指向一个 redisReply 类型的指针,一般强制转换成为redisReply类型的进行进一步的处理。
(redisReply 的定义)
在这里插入图片描述

  • REDIS_REPLY_STRING == 1:返回值是字符串,字符串储存在 redis->str 当中,字符串长度为 redis->len。
  • REDIS_REPLY_ARRAY == 2:返回值是数组,数组大小存在 redis->elements 里面,数组值存储在 redis->element[i]里面。数组里面存储的是指向 redisReply 的指针,数组里面的返回值可以通过 redis->element[i]->str 来访问,数组的结果里全是type==REDIS_REPLY_STRING 的 redisReply 对象指针
  • REDIS_REPLY_INTEGER == 3:返回值为整数 long long。
  • REDIS_REPLY_NIL==4:返回值为空表示执行结果为空。
  • REDIS_REPLY_STATUS ==5:返回命令执行的状态,比如 set foo bar 返回的状态为 OK,存储在 str 当中 reply->str == “OK”。
  • REDIS_REPLY_ERROR ==6 :命令执行错误,错误信息存放在 reply->str 当中。
  • 代码
--举例1:授权(输入密码)
redisReply *reply = (redisReply *)(redisCommand(context, "auth 0voice"));
printf("type : %d\n", reply->type);
if (reply->type == REDIS_REPLY_STATUS) {
    /*SET str Hello World*/
    printf("auth ok\n");
}
freeReplyObject(reply);

--举例2:输入命令
    // GET Key
    int key_1 = 1;
    reply = (redisReply *)(redisCommand(context, "GET %d", key_1));
    if (reply->type == REDIS_REPLY_STRING) {//REDIS_REPLY_STRING == 1:返回值是 字符串
        /*GET str Hello World*/
        printf("GET str %s\n", reply->str); //字符串储存在 redis->str 当中
        /*GET len 11*/
        printf("GET len %ld\n", reply->len);//字符串长度为 redis->len
    }
    freeReplyObject(reply);

1.3 void freeReplyObject(void *reply);

  • 说明

释放redisCommand执行后返回的redisReply所占用的内存

  • 返回

返回redisReply所占用的内存

  • 代码

如上面代码所示

1.4 void redisFree(redisContext *c);

  • 说明:

说明:释放redisConnect()所产生的连接。

  • 代码
redisFree(context);//举例上面的context

二、异步函数接口

2.0 redisAsyncContext结构体介绍

简单描述
类似于同步操作API,异步操作API中也有一个上下文结构redisAsyncContext,用于维护异步链接中的各种状态。redisAsyncContext结构在同步上下文结构redisContext的基础上,增加了一些异步属性,它的定义如下:

typedef struct redisAsyncContext {
    /* Hold the regular context, so it can be realloc'ed. */
    redisContext c;
 
    /* Setup error flags so they can be used directly. */
    int err;
    char *errstr;
 
    /* Not used by hiredis */
    void *data;
 
    /* Event library data and hooks */
    struct {
        void *data;
 
        /* Hooks that are called when the library expects to start
         * reading/writing. These functions should be idempotent. */
        void (*addRead)(void *privdata);
        void (*delRead)(void *privdata);
        void (*addWrite)(void *privdata);
        void (*delWrite)(void *privdata);
        void (*cleanup)(void *privdata);
    } ev;
 
    /* Called when either the connection is terminated due to an error or per
     * user request. The status is set accordingly (REDIS_OK, REDIS_ERR). */
    redisDisconnectCallback *onDisconnect;
 
    /* Called when the first write event was received. */
    redisConnectCallback *onConnect;
 
    /* Regular command callbacks */
    redisCallbackList replies;
 
    /* Subscription callbacks */
    struct {
        redisCallbackList invalid;
        struct dict *channels;
        struct dict *patterns;
    } sub;
} redisAsyncContext;
  • 结构体函数说明

1.回调函数onDisconnect,表示断链时会调用的函数,该属性可以通过redisAsyncSetDisconnectCallback函数设置;
2.回调函数onConnect,表示TCP建链成功或失败之后会调用的函数,该属性可以通过redisAsyncSetConnectCallback函数设置;
3.replies属性是一个redisCallbackList结构,也就是由回调结构redisCallback组成的单链表。当发送普通命令时,会依次将该命令对应的回调结构追加到链表中,当Redis服务器回复普通命令时,会依次调用该链表中的每个redisCallback结构中的回调函数
4. 结构体sub用于处理订阅模式,其中的字典channels,以频道名为key,以回调结构redisCallback为value。当客户端使用Hiredis异步API发送”subscribe”命令后,服务器产生回复时,就会根据回复信息中的频道名查询字典channels,找到对应的回调结构,调用其中的回调函数。字典patterns与channels类似,只不过它用于”psubscirbe”命令,其中的key是频道名模式;回调链表invalid,当客户端处于订阅模式下,服务器发来了意想不到的回复时,会依次调用该链表中,每个回调结构中的回调函数

2.1 建立连接

redisAsyncContext *redisAsyncConnect(const char *ip, int port);执行异步操作中的TCP建链
  • 说明:

函数redisAsyncConnect执行异步操作中的TCP建链,该函数首先根据ip和port,调用redisConnectNonBlock函数向Redis服务器发起非阻塞的建链操作,然后调用redisAsyncInitialize函数创建异步上下文结构redisAsyncContext。

  • 源码
redisAsyncContext *redisAsyncConnect(const char *ip, int port) {
    redisContext *c;
    redisAsyncContext *ac;
 
    c = redisConnectNonBlock(ip,port);//向Redis服务器发起非阻塞的建链操作
    if (c == NULL)
        return NULL;
 
    ac = redisAsyncInitialize(c);//创建异步上下文结构redisAsyncContext
    if (ac == NULL) {
        redisFree(c);
        return NULL;
    }
 
    __redisAsyncCopyError(ac);
    return ac;
}
redisAsyncSetConnectCallbac设置异步上下文中的建链回调函数
  • 代码
int redisAsyncSetConnectCallback(redisAsyncContext *ac, redisConnectCallback *fn) {
    if (ac->onConnect == NULL) {
        ac->onConnect = fn;
 
        /* The common way to detect an established connection is to wait for
         * the first write event to be fired. This assumes the related event
         * library functions are already set. */
        _EL_ADD_WRITE(ac);
        return REDIS_OK;
    }
    return REDIS_ERR;
}
  • 函数说明

该函数中,如果之前已经设置过建链回调函数了,则直接返回REDIS_ERR。该函数除了设置异步上下文中的建链回调函数之外,还会调用_EL_ADD_WRITE,注册可写事件。对于使用Redis的ae事件库的客户端来说,该宏定义实际上就是调用redisAeAddWrite函数:

static void redisAeAddWrite(void *privdata) {
    redisAeEvents *e = (redisAeEvents*)privdata;
    aeEventLoop *loop = e->loop;
    if (!e->writing) {
        e->writing = 1;
        aeCreateFileEvent(loop,e->fd,AE_WRITABLE,redisAeWriteEvent,e);
    }
}
  • 补充

可写事件的回调函数是redisAeWriteEvent,该函数调用redisAsyncHandleWrite实现

redisAsyncHandleWrite处理建链
  • 代码
void redisAsyncHandleWrite(redisAsyncContext *ac) {
    redisContext *c = &(ac->c);
    int done = 0;
 
    if (!(c->flags & REDIS_CONNECTED)) {
        /* Abort connect was not successful. */
        if (__redisAsyncHandleConnect(ac) != REDIS_OK)
            return;
        /* Try again later when the context is still not connected. */
        if (!(c->flags & REDIS_CONNECTED))
            return;
    }
    . . .
}
  • 函数说明

在该函数中,如果上下文标志位中还没有设置REDIS_CONNECTED标记,说明目前还没有检测是否建链成功,因此调用__redisAsyncHandleConnect,判断建链是否成功,如果建链成功,则会在异步上下文的标志位中增加REDIS_CONNECTED标记,如果还没有建链成功,则直接返回

__redisAsyncHandleConnect的代码如下:

static int __redisAsyncHandleConnect(redisAsyncContext *ac) {
    redisContext *c = &(ac->c);
 
    if (redisCheckSocketError(c) == REDIS_ERR) {//判断当前TCP是否建链成功
        /* Try again later when connect(2) is still in progress. */
        if (errno == EINPROGRESS)//如果该函数返回REDIS_ERR,在errno为EINPROGRESS的情况下,说明TCP尚在建链中,这种情况直接返回REDIS_OK,等待下次处理
            return REDIS_OK;
 
        if (ac->onConnect) ac->onConnect(ac,REDIS_ERR);//其他情况说明建链失败,以REDIS_ERR为参数,调用异步上下文中的建链回调函数,然后调用__redisAsyncDisconnect做清理工作,最后返回REDIS_ERR;
        __redisAsyncDisconnect(ac);
        return REDIS_ERR;
    }
 
    /* Mark context as connected. */
    c->flags |= REDIS_CONNECTED;//如果redisCheckSocketError函数返回REDIS_OK,则将REDIS_CONNECTED标记增加到上下文标志位中,并以REDIS_OK为参数调用异步上下文中的建链回调函数;最后返回REDIS_OK
    if (ac->onConnect) ac->onConnect(ac,REDIS_OK);
    return REDIS_OK;
}

2.2 发送命令,接受回复

redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *format, …);向redis发送命令的异步API
  • 参数说明:

fn:表示收到命令回复后要调用的回调函数
privdata:表示收到命令回复后要调用的回调函数的参数

  • 函数说明:

因为Redis是单线程处理命令,因此当客户端使用异步API与事件库的结合之后,命令就自动的管道化了。也就是客户端在单线程模式下,发送命令的顺序和接收回复的顺序是一致的。因此,当发送命令时,就会将回调函数fn和参数privdata封装成回调结构redisCallback,并将该结构记录到单链表或者字典中。当收到回复后,就会依次得到链表或者字典中的redisCallback结构,调用其中的回调函数

  • 代码流程说明

循环调用:
①redisAsyncCommand函数->redisvAsyncCommand函数->调用了
②redisvFormatCommand:解析用户输入的命令,转换成统一请求协议格式的字符串cmd,然后
③然后调用__redisAsyncCommand函数,将cmd发送给Redis,并且记录相应的回调函数

  • 代码
static int __redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, char *cmd, size_t len) {
    redisContext *c = &(ac->c);
    redisCallback cb;
    int pvariant, hasnext;
    char *cstr, *astr;
    size_t clen, alen;
    char *p;
    sds sname;
 
    /* Don't accept new commands when the connection is about to be closed. */
    if (c->flags & (REDIS_DISCONNECTING | REDIS_FREEING)) return REDIS_ERR;
 
    /* Setup callback */
    //1.首先将回调函数fn,以及用户提供的该回调函数的私有参数privdata,封装到redisCallback回调结构的cb中。当然,用户如果没有提供回调函数和参数,则cb中相应的属性为NULL
    cb.fn = fn;
    cb.privdata = privdata;
 	
 	//2.然后解析用户输入命令,根据不同的命令,将回调函数追加到不同的链表或字典中
    /* Find out which command will be appended. */
    p = nextArgument(cmd,&cstr,&clen);
    assert(p != NULL);
    hasnext = (p[0] == '$');
    pvariant = (tolower(cstr[0]) == 'p') ? 1 : 0;
    cstr += pvariant;
    clen -= pvariant;
 	
 	//3. 如果用户输入命令为"subscribe"或者"psubscribe",首先将REDIS_SUBSCRIBED标记增加到上下文标志中,表示当前客户端进入订阅模式
    if (hasnext && strncasecmp(cstr,"subscribe\r\n",11) == 0) {
        c->flags |= REDIS_SUBSCRIBED;
 
        /* Add every channel/pattern to the list of subscription callbacks. */
        while ((p = nextArgument(p,&astr,&alen)) != NULL) {
            sname = sdsnewlen(astr,alen);
            if (pvariant)
                dictReplace(ac->sub.patterns,sname,&cb);
            else
                dictReplace(ac->sub.channels,sname,&cb);
        }
    //4.如果用户输入命令为"unsubscribe",这种情况无需记录回调函数。但是该命令只有客户端处于订阅模式下才有效,否则直接返回REDIS_ERR;
    } else if (strncasecmp(cstr,"unsubscribe\r\n",13) == 0) {
        /* It is only useful to call (P)UNSUBSCRIBE when the context is
         * subscribed to one or more channels or patterns. */
        if (!(c->flags & REDIS_SUBSCRIBED)) return REDIS_ERR;
 
        /* (P)UNSUBSCRIBE does not have its own response: every channel or
         * pattern that is unsubscribed will receive a message. This means we
         * should not append a callback function for this command. */
   //5.如果用户输入命令为"monitor",则将REDIS_MONITORING标记增加到上下文标志位中,表示客户端进入monitor模式,然后调用__redisPushCallback,将回调结构cb追加到上下文的回调链表ac->replies中;	
     } else if(strncasecmp(cstr,"monitor\r\n",9) == 0) {
         /* Set monitor flag and push callback */
         c->flags |= REDIS_MONITORING;
         __redisPushCallback(&ac->replies,&cb);
   //6. 如果用户输入的是其他命令,则若当前客户端处于订阅模式,因处于订阅模式中,客户端只能发送”subscribe/psubscribe/unsubscribe/punsubscribe”命令,走到这一步,说明客户端发送了其他命令,因此将回调结构cb追加到链表ac->sub.invalid中;
    } else {
        if (c->flags & REDIS_SUBSCRIBED)
            /* This will likely result in an error reply, but it needs to be
             * received and passed to the callback. */
            __redisPushCallback(&ac->sub.invalid,&cb);
   //7.其他情况,将回调结构cb追加到链表ac->replies中;记录回调函数
        else
            __redisPushCallback(&ac->replies,&cb);
    }
 	
 	//8.调用__redisAppendCommand,将cmd追加到上下文的输出缓存中
    __redisAppendCommand(c,cmd,len);
 	
 	//9.然后调用_EL_ADD_WRITE,注册可写事件。对于使用Redis的ae事件库的客户端来说,该宏定义实际上就是调用redisAeAddWrite函数,可写事件的回调函数是redisAeWriteEvent,该函数调用redisAsyncHandleWrite实现。
    /* Always schedule a write when the write buffer is non-empty */
    _EL_ADD_WRITE(ac);
 
    return REDIS_OK;
}

redisAsyncHandleWrite函数的全部代码如下:

void redisAsyncHandleWrite(redisAsyncContext *ac) {
    redisContext *c = &(ac->c);
    int done = 0;
    
 	//1.首先处理建链尚未成功的情况
    if (!(c->flags & REDIS_CONNECTED)) {
        /* Abort connect was not successful. */
        if (__redisAsyncHandleConnect(ac) != REDIS_OK)
            return;
        /* Try again later when the context is still not connected. */
        if (!(c->flags & REDIS_CONNECTED))
            return;
    }
 	
 	//2.建链成功之后,调用redisBufferWrite,将上下文中输出缓存的内容通过socket描述符发送出去。
    if (redisBufferWrite(c,&done) == REDIS_ERR) {
        __redisAsyncDisconnect(ac);
    } else {
        /* Continue writing when not done, stop writing otherwise */
        //如果没发成功,再注册可写事件
        if (!done)
            _EL_ADD_WRITE(ac);
       	//全部发送成功之后,调用_EL_DEL_WRITE,删除注册的可写事件。对于使用Redis的ae事件库的客户端来说,这里就是调用redisAeDelWrite函数,删除注册的可写事件。
        else
            _EL_DEL_WRITE(ac);
 
        /* Always schedule reads after writes */
        // 然后,调用_EL_ADD_READ,注册可读事件。对于使用Redis的ae事件库的客户端来说,这里就是调用redisAeAddRead函数,注册可读事件。事件回调函数为redisAeReadEvent。该回调函数主要是调用redisAsyncHandleRead实现
        _EL_ADD_READ(ac);
    }
}

redisAsyncHandleRead函数的代码如下:

void redisAsyncHandleRead(redisAsyncContext *ac) {
    redisContext *c = &(ac->c);
    
 	//1.首先处理未建链的情况
    if (!(c->flags & REDIS_CONNECTED)) {
        /* Abort connect was not successful. */
        if (__redisAsyncHandleConnect(ac) != REDIS_OK)
            return;
        /* Try again later when the context is still not connected. */
        if (!(c->flags & REDIS_CONNECTED))
            return;
    }
 	
    if (redisBufferRead(c) == REDIS_ERR) {
        __redisAsyncDisconnect(ac);
    } else {
    //2.建链成功之后,首先调用redisBufferRead,从socket中读取数据,并追加到解析器的输入缓存中,这在同步操作API中已讲过,不再赘述。
        /* Always re-schedule reads */
        _EL_ADD_READ(ac);
   //3.读取成功之后,调用redisProcessCallbacks函数进行处理。该函数就是根据回复信息找到相应的回调结构,然后调用其中的回调函数
        redisProcessCallbacks(ac);
    }
}

redisProcessCallbacks函数的代码如下

void redisProcessCallbacks(redisAsyncContext *ac) {
    redisContext *c = &(ac->c);
    redisCallback cb = {NULL, NULL, NULL};
    void *reply = NULL;
    int status;
 	
 	//1.该函数循环调用redisGetReply,将解析器中输入缓存中的内容,组织成redisReply结构树,树的根节点通过参数reply返回
    while((status = redisGetReply(c,&reply)) == REDIS_OK) {
    	//2. 在循环中,如果取得的reply为NULL,说明输入缓存已空,这种情况下,如果当前上下文标志位中设置了REDIS_DISCONNECTING,说明之前某个命令的回调函数中,调用了redisAsyncDisconnect函数设置了该标记,因此在输出缓存为空,并且输入缓存也为空(reply为NULL)的条件下,调用__redisAsyncDisconnect开始执行断链操作,释放清理内存,最后返回。
        if (reply == NULL) {
            /* When the connection is being disconnected and there are
             * no more replies, this is the cue to really disconnect. */
            if (c->flags & REDIS_DISCONNECTING && sdslen(c->obuf) == 0) {
                __redisAsyncDisconnect(ac);
                return;
            }
 			//3.如果取得的reply为NULL,并且当前处于监控模式下,则将上次取出的回调结构cb,重新插入到链表ac->replies中。最后退出循环。
            /* If monitor mode, repush callback */
            if(c->flags & REDIS_MONITORING) {
                __redisPushCallback(&ac->replies,&cb);
            }
 
            /* When the connection is not being disconnected, simply stop
             * trying to get replies and wait for the next loop tick. */
            break;
        }
        
 		//4. 如果取得的reply非空,则首先调用__redisShiftCallback,尝试从链表ac->replies中取出第一个回调结构cb。
        /* Even if the context is subscribed, pending regular callbacks will
         * get a reply before pub/sub messages arrive. */
        if (__redisShiftCallback(&ac->replies,&cb) != REDIS_OK) {
            /*
             * A spontaneous reply in a not-subscribed context can be the error
             * reply that is sent when a new connection exceeds the maximum
             * number of allowed connections on the server side.
             *
             * This is seen as an error instead of a regular reply because the
             * server closes the connection after sending it.
             *
             * To prevent the error from being overwritten by an EOF error the
             * connection is closed here. See issue #43.
             *
             * Another possibility is that the server is loading its dataset.
             * In this case we also want to close the connection, and have the
             * user wait until the server is ready to take our request.
             */
            if (((redisReply*)reply)->type == REDIS_REPLY_ERROR) {
                c->err = REDIS_ERR_OTHER;
                snprintf(c->errstr,sizeof(c->errstr),"%s",((redisReply*)reply)->str);
                c->reader->fn->freeObject(reply);
                __redisAsyncDisconnect(ac);
                return;
            }
            /* No more regular callbacks and no errors, the context *must* be subscribed or monitoring. */
            assert((c->flags & REDIS_SUBSCRIBED || c->flags & REDIS_MONITORING));
            if(c->flags & REDIS_SUBSCRIBED)
                __redisGetSubscribeCallback(ac,reply,&cb);
        }
 
        if (cb.fn != NULL) {
            __redisRunCallback(ac,&cb,reply);
            c->reader->fn->freeObject(reply);
 
            /* Proceed with free'ing when redisAsyncFree() was called. */
            if (c->flags & REDIS_FREEING) {
                __redisAsyncFree(ac);
                return;
            }
        } else {
            /* No callback for this reply. This can either be a NULL callback,
             * or there were no callbacks to begin with. Either way, don't
             * abort with an error, but simply ignore it because the client
             * doesn't know what the server will spit out over the wire. */
            c->reader->fn->freeObject(reply);
        }
    }
 
    /* Disconnect when there was an error reading the reply */
    if (status != REDIS_OK)
        __redisAsyncDisconnect(ac);
}
1.如果取得的reply非空,则首先调用__redisShiftCallback,尝试从链表ac->replies中取出第一个回调结构cb。

2.如果链表ac->replies已空,这种情况下,客户端要么是处于订阅模式下,要么就是服务器主动向客户端发送了某个错误信息,比如该客户端向服务器建链,服务器中已经超过了最大的客户端数,或者是服务器正在加载转储数据,而向客户端返回一个错误信息。

3.如果回复类型为REDIS_REPLY_ERROR,则调用__redisAsyncDisconnect断链;如果回复类型不是REDIS_REPLY_ERROR,则当前客户端只能处于订阅模式或者监控模式,如果当前处于订阅模式下,则调用__redisGetSubscribeCallback,根据reply,从相应的字典中取出回调结构cb;

4.取得回调结构cb之后,只要其中的回调函数不为空,就调用__redisRunCallback函数,调用其中的回调函数;对于回调函数为空的回调结构,直接释放reply即可。

__redisGetSubscribeCallback函数根据回复信息,在字典结构中找到对应的回调结构并返回该结构。它的代码如下:

static int __redisGetSubscribeCallback(redisAsyncContext *ac, redisReply *reply, redisCallback *dstcb) {
    redisContext *c = &(ac->c);
    dict *callbacks;
    dictEntry *de;
    int pvariant;
    char *stype;
    sds sname;
 
    /* Custom reply functions are not supported for pub/sub. This will fail
     * very hard when they are used... */
    if (reply->type == REDIS_REPLY_ARRAY) {
        assert(reply->elements >= 2);
        assert(reply->element[0]->type == REDIS_REPLY_STRING);
        stype = reply->element[0]->str;
        pvariant = (tolower(stype[0]) == 'p') ? 1 : 0;
 
        if (pvariant)
            callbacks = ac->sub.patterns;
        else
            callbacks = ac->sub.channels;
 
        /* Locate the right callback */
        assert(reply->element[1]->type == REDIS_REPLY_STRING);
        sname = sdsnewlen(reply->element[1]->str,reply->element[1]->len);
        de = dictFind(callbacks,sname);
        if (de != NULL) {
            memcpy(dstcb,dictGetEntryVal(de),sizeof(*dstcb));
 
            /* If this is an unsubscribe message, remove it. */
            if (strcasecmp(stype+pvariant,"unsubscribe") == 0) {
                dictDelete(callbacks,sname);
 
                /* If this was the last unsubscribe message, revert to
                 * non-subscribe mode. */
                assert(reply->element[2]->type == REDIS_REPLY_INTEGER);
                if (reply->element[2]->integer == 0)
                    c->flags &= ~REDIS_SUBSCRIBED;
            }
        }
        sdsfree(sname);
    } else {
        /* Shift callback for invalid commands. */
        __redisShiftCallback(&ac->sub.invalid,dstcb);
    }
    return REDIS_OK;
}

正常情况下,处于订阅模式下的客户端,接收到的消息类型应该是REDIS_REPLY_ARRAY类型,比如:

1) "message"  
2) "channel1"  
3) "hi  
1) "pmessage"  
2) "channel.?*"  
3) "channel.1"  
4) "this is channel.1"  
1.根据回复信息第一行的首字节是否为”p”,找到不同的字典结构callbacks。然后根据reply->element[1]的内容,也就是频道名或者频道名模式,从字典中找到相应的回调结构。
2.如果Redis回复的信息是"unsubscribe",则从字典中删除相应的回调结构,此时reply->element[2]中的信息应该是个整数,表示当前客户端目前还订阅了多少频道,如果该值为0,表示客户端已经从最后一个频道中退订了,因此将REDIS_SUBSCRIBED标记从标志位c->flags中删除,表示该客户端退出订阅模式;
3.如果Redis的回复信息不是REDIS_REPLY_ARRAY类型,说明发生了异常,此时从链表ac->sub.invalid中取出下一个回调结构即可。

2.3 redisAsyncDisconnect断开链接

客户端可以通过调用redisAsyncDisconnect函数主动断链。该函数的代码如下:

void redisAsyncDisconnect(redisAsyncContext *ac) {
    redisContext *c = &(ac->c);
    c->flags |= REDIS_DISCONNECTING;
    if (!(c->flags & REDIS_IN_CALLBACK) && ac->replies.head == NULL)
        __redisAsyncDisconnect(ac);
}
1. 一般情况下,该函数是在某个命令回调函数中被调用。当调用该函数时,并不一定会立即进行断链操作,该函数将REDIS_DISCONNECTING标记增加到上下文的标志位中。只有当输出缓存中所有命令都发送完毕,并且收到他们的回复,调用了回调函数之后,才会真正的执行断链操作,这是在函数redisProcessCallbacks中处理的。

2.设置了REDIS_DISCONNECTING标记后,在__redisAsyncCommand函数中,会直接返回REDIS_ERR,表示不再发送新的命令。

3.真正的断链操作由函数__redisAsyncDisconnect实现。

当客户与服务器之间的交互过程中发生了错误,或者是服务器主动断链时,就会调用__redisAsyncDisconnect进入断链流程。该函数代码如下:

static void __redisAsyncDisconnect(redisAsyncContext *ac) {
    redisContext *c = &(ac->c);
 
    /* Make sure error is accessible if there is any */
    __redisAsyncCopyError(ac);
 
    if (ac->err == 0) {
        /* For clean disconnects, there should be no pending callbacks. */
        assert(__redisShiftCallback(&ac->replies,NULL) == REDIS_ERR);
    } else {
        /* Disconnection is caused by an error, make sure that pending
         * callbacks cannot call new commands. */
        c->flags |= REDIS_DISCONNECTING;
    }
 
    /* For non-clean disconnects, __redisAsyncFree() will execute pending
     * callbacks with a NULL-reply. */
    __redisAsyncFree(ac);
}
首先调用__redisAsyncCopyError,得到异步上下文中的err,如果err为0,则说明是客户端主动断链,这种情况下,链表ac->replies应该为空才对;否则,将上下文标志位中增加REDIS_DISCONNECTING标记,表明这是由于错误引起的断链,设置该标记后,不再发送新的命令给Redis。

         最终调用__redisAsyncFree函数,进行最后的清理。在__redisAsyncFree函数中,会议NULL为reply,调用所有异步上下文中尚存的回调函数。然后调用断链回调函数,最后调用redisFree关闭socket描述符,清理释放空间。

三、封装hiredis实现数据库代理服务器用到的接口

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值