用户工具

站点工具


about_redis_16

Redis的那些事儿 第十六章 Connection相关命令的实现

作者:陈科

联系方式:chenke1818@gmail.com

转载请说明出处:http://www.dumpcache.com/wiki/doku.php?id=about_redis_16

1.AUTH命令实现

void authCommand(redisClient *c) {
    if (!server.requirepass) {
        addReplyError(c,"Client sent AUTH, but no password is set");
    } else if (!time_independent_strcmp(c->argv[1]->ptr, server.requirepass)) {
      c->authenticated = 1;
      addReply(c,shared.ok);
    } else {
      c->authenticated = 0;
      addReplyError(c,"invalid password");
    }
}

假如服务器需要密码,那么就进行密码的比对,如果鉴权成功,则:c→authenticated = 1

2.ECHO命令实现

void echoCommand(redisClient *c) {
    addReplyBulk(c,c->argv[1]);
}

直接将用户的输入返回给客户端

3.PING命令实现

void pingCommand(redisClient *c) {
    /* The command takes zero or one arguments. */
    if (c->argc > 2) {
        addReplyErrorFormat(c,"wrong number of arguments for '%s' command",
            c->cmd->name);
        return;
    }
 
    if (c->flags & REDIS_PUBSUB) {
        addReply(c,shared.mbulkhdr[2]);
        addReplyBulkCBuffer(c,"pong",4);
        if (c->argc == 1)
            addReplyBulkCBuffer(c,"",0);
        else
            addReplyBulk(c,c->argv[1]);
    } else {
        if (c->argc == 1)
            addReply(c,shared.pong);
        else
            addReplyBulk(c,c->argv[1]);
    }
}

返回PONG给客户端

4.SELECT命令实现

客户端进行指定ID数据库的选择

void selectCommand(redisClient *c) {
    long id;
 
    if (getLongFromObjectOrReply(c, c->argv[1], &id,
        "invalid DB index") != REDIS_OK)
        return;
 
    if (selectDb(c,id) == REDIS_ERR) {
        addReplyError(c,"invalid DB index");
    } else {
        addReply(c,shared.ok);
    }
}
about_redis_16.txt · 最后更改: 2018/10/14 15:31 (外部编辑)