走近源码:Redis 命令执行过程(客户端)

栏目: C · 发布时间: 5年前

内容简介:More Redis internals: Tracing a GET & SET

前面我们了解过了当 Redis 执行一个命令时,服务端做了哪些事情,不了解的同学可以看一下这篇文章走近源码:Redis如何执行命令。今天就一起来看看Redis的命令执行过程中客户端都做了什么事情。

启动客户端

首先看redis-cli.c文件的main函数,也就是我们输入redis-cli命令时所要执行的函数。main函数主要是给config变量的各个属性设置默认值。比如:

  • hostip:要连接的服务端的IP,默认为127.0.0.1

  • hostport:要连接的服务端的端口,默认为6379

  • interactive:是否是交互模式,默认为0(非交互模式)

  • 一些模式的设置,例如:cluster_mode、slave_mode、getrdb_mode、scan_mode等

  • cluster相关的参数

……

接着调用parseOptions()函数来处理参数,例如-p、-c、--verbose等一些用来指定config属性的(可以输入redis-cli --help查看)或是指定启动模式的。

处理完这些参数后,需要把它们从参数列表中去除,剩下用于在非交互模式中执行的命令。

parseEnv()用来判断是否需要验证权限,紧接着就是根据刚才的参数判断需要进入哪种模式,是cluster还是slave又或者是RDB……如果没有进入这些模式,并且没有需要执行的命令,那么就进入交互模式,否则会进入非交互模式。

 1/* Start interactive mode when no command is provided */
 2if (argc == 0 && !config.eval) {
 3    /* Ignore SIGPIPE in interactive mode to force a reconnect */
 4    signal(SIGPIPE, SIG_IGN);
 5
 6    /* Note that in repl mode we don't abort on connection error.
 7     * A new attempt will be performed for every command send. */
 8    cliConnect(0);
 9    repl();
10}
11
12/* Otherwise, we have some arguments to execute */
13if (cliConnect(0) != REDIS_OK) exit(1);
14if (config.eval) {
15    return evalMode(argc,argv);
16} else {
17    return noninteractive(argc,convertToSds(argc,argv));
18}

连接服务器

cliConnect()函数用于连接服务器,它的参数是一个标志位,如果是CC_FORCE(0)表示强制重连,如果是CC_QUIET(2)表示不打印错误日志。

如果建立了socket,那么就连接这个socket,否则就去连接指定的IP和端口。

1if (config.hostsocket == NULL) {
2    context = redisConnect(config.hostip,config.hostport);
3} else {
4    context = redisConnectUnix(config.hostsocket);
5}

redisConnect

redisConnect()(在deps/hiredis/hiredis.c文件中)函数用于连接指定的IP和端口的redis实例。它的返回值是redisContext类型的。这个结构封装了一些客户端与服务端之间的连接状态,obuf是用来存放返回结果的缓冲区,同时还有客户端与服务端的协议。

 1//hiredis.h
 2/* Context for a connection to Redis */
 3typedef struct redisContext {
 4    int err; /* Error flags, 0 when there is no error */
 5    char errstr[128]; /* String representation of error when applicable */
 6    int fd;
 7    int flags;
 8    char *obuf; /* Write buffer */
 9    redisReader *reader; /* Protocol reader */
10
11    enum redisConnectionType connection_type;
12    struct timeval *timeout;
13
14    struct {
15        char *host;
16        char *source_addr;
17        int port;
18    } tcp;
19
20    struct {
21        char *path;
22    } unix_sock;
23
24} redisContext;

redisConnect的实现比较简单,首先初始化一个redisContext变量,然后把客户端的flags字段设置为阻塞状态,接着调用redisContextConnectTcp命令。

 1redisContext *redisConnect(const char *ip, int port) {
 2    redisContext *c;
 3
 4    c = redisContextInit();
 5    if (c == NULL)
 6        return NULL;
 7
 8    c->flags |= REDIS_BLOCK;
 9    redisContextConnectTcp(c,ip,port,NULL);
10    return c;
11}

redisContextConnectTcp

redisContextConnectTcp()函数在net.c文件中,它调用的是_redisContextConnectTcp()这个函数,所以我们主要关注这个函数。它用来与服务端创建TCP连接,首先调整了tcp的host和timeout字段,然后getaddrinfo获取要连接的服务信息,这里兼容了IPv6和IPv4。然后尝试连接服务端。

 1if (connect(s,p->ai_addr,p->ai_addrlen) == -1) {
 2    if (errno == EHOSTUNREACH) {
 3        redisContextCloseFd(c);
 4        continue;
 5    } else if (errno == EINPROGRESS && !blocking) {
 6        /* This is ok. */
 7    } else if (errno == EADDRNOTAVAIL && reuseaddr) {
 8        if (++reuses >= REDIS_CONNECT_RETRIES) {
 9            goto error;
10        } else {
11            redisContextCloseFd(c);
12            goto addrretry;
13        }
14    } else {
15        if (redisContextWaitReady(c,timeout_msec) != REDIS_OK)
16            goto error;
17    }
18}

connect()函数用于去连接服务器,连接上之后,服务器端会调用accept函数。如果连接失败,也会根据情况决定是否要关闭redisContext文件描述符。

发送命令并接收返回

当客户端和服务端建立连接之后,客户端向服务器端发送命令并接收返回值了。

repl

我们回到redis-cli.c文件中的repl()函数,这个函数就是用来向服务器端发送命令并且接收到的结果返回。

这里首先调用了cliInitHelp()和cliIntegrateHelp()这两个函数,初始化了一些帮助信息,然后设置了一些回调的方法。如果是终端模式,则会从rc文件中加载历史命令。然后调用linenoise()函数读取用户输入的命令,并以空格分隔参数。

1nread = read(l.ifd,&c,1);

接下来是判断是否需要过滤掉重复的参数。

issueCommandRepeat

生成好命令后,就调用issueCommandRepeat()函数开始执行命令。

 1static int issueCommandRepeat(int argc, char **argv, long repeat) {
 2    while (1) {
 3        config.cluster_reissue_command = 0;
 4        if (cliSendCommand(argc,argv,repeat) != REDIS_OK) {
 5            cliConnect(CC_FORCE);
 6
 7            /* If we still cannot send the command print error.
 8             * We'll try to reconnect the next time. */
 9            if (cliSendCommand(argc,argv,repeat) != REDIS_OK) {
10                cliPrintContextError();
11                return REDIS_ERR;
12            }
13         }
14         /* Issue the command again if we got redirected in cluster mode */
15         if (config.cluster_mode && config.cluster_reissue_command) {
16            cliConnect(CC_FORCE);
17         } else {
18             break;
19        }
20    }
21    return REDIS_OK;
22}

这个函数会调用cliSendCommand()函数,将命令发送给服务器端,如果发送失败,会强制重连一次,然后再次发送命令。

redisAppendCommandArgv

cliSendCommand()函数又会调用redisAppendCommandArgv()函数(在hiredis.c文件中)这个函数是按照Redis协议将命令进行编码。

cliReadReply

然后调用cliReadReply()函数,接收服务器端返回的结果,调用cliFormatReplyRaw()函数将结果进行编码并返回。

举个栗子

我们以GET命令为例,具体描述一下,从客户端到服务端,程序是如何运行的。

我们用gdb调试redis-server,将断点设置到readQueryFromClient函数这里。

 1gdb src/redis-server 
 2GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git
 3Copyright (C) 2018 Free Software Foundation, Inc.
 4License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
 5This is free software: you are free to change and redistribute it.
 6There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
 7and "show warranty" for details.
 8This GDB was configured as "x86_64-linux-gnu".
 9Type "show configuration" for configuration details.
10For bug reporting instructions, please see:
11<http://www.gnu.org/software/gdb/bugs/>.
12Find the GDB manual and other documentation resources online at:
13<http://www.gnu.org/software/gdb/documentation/>.
14For help, type "help".
15Type "apropos word" to search for commands related to "word"...
16Reading symbols from src/redis-server...done.
17(gdb) b readQueryFromClient
18Breakpoint 1 at 0x43c520: file networking.c, line 1379.
19(gdb) run redis.conf

然后再调试redis-cli,断点设置cliReadReply函数。

 1gdb src/redis-cli 
 2GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git
 3Copyright (C) 2018 Free Software Foundation, Inc.
 4License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
 5This is free software: you are free to change and redistribute it.
 6There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
 7and "show warranty" for details.
 8This GDB was configured as "x86_64-linux-gnu".
 9Type "show configuration" for configuration details.
10For bug reporting instructions, please see:
11<http://www.gnu.org/software/gdb/bugs/>.
12Find the GDB manual and other documentation resources online at:
13<http://www.gnu.org/software/gdb/documentation/>.
14For help, type "help".
15Type "apropos word" to search for commands related to "word"...
16Reading symbols from src/redis-cli...done.
17(gdb) b cliReadReply
18Breakpoint 1 at 0x40ffa0: file redis-cli.c, line 845.
19(gdb) run

在客户端输入get命令,发现程序在断点处停止。

1127.0.0.1:6379> get jackey
2
3Breakpoint 1, cliReadReply (output_raw_strings=output_raw_strings@entry=0)
4    at redis-cli.c:845
5845    static int cliReadReply(int output_raw_strings) {

我们可以看到这时Redis已经准备好将命令发送给服务端了,先来查看一下要发送的内容。

1(gdb) p context->obuf
2$1 = 0x684963 "*2\r\n$3\r\nget\r\n$6\r\njackey\r\n"

把\r\n替换成换行符看的后是这样:

1*2
2$3
3get
4$6
5jackey

*2表示命令参数的总数,包括命令的名字,也就是告诉服务端应该处理两个参数。

get是命令名,也就是第一个参数。

6表示第二个参数的长度。

jackey是第二个参数。

当程序运行到redisGetReply时就会把命令发送给服务端了,这时我们再来看服务端的运行情况。

1Thread 1 "redis-server" hit Breakpoint 1, readQueryFromClient (
2    el=0x7ffff6a41050, fd=7, privdata=0x7ffff6b1e340, mask=1)
3    at networking.c:1379
41379    void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
5(gdb) 

程序调整到

1sdsIncrLen(c->querybuf,nread);

这时nread的内容会被加到c->querybuf中,我们来看一下是不是我们发送过来的命令。

1(gdb) p c->querybuf
2$1 = (sds) 0x7ffff6a75cc5 "*2\r\n$3\r\nget\r\n$6\r\njackey\r\n"

到这里,Redis的服务端已经接受到请求了。接下来就是处理命令的过程,前文我们提到Redis是在processCommand()函数中处理的。

processCommand()函数会调用lookupCommand()函数,从redisCommandTable表中查询出要执行的函数。然后调用c->cmd->proc(c)执行这个函数,这里我们get命令对应的是getCommand函数,getCommand里只是调用了getGenericCommand()函数。

 1//t_string.c
 2int getGenericCommand(client *c) {
 3    robj *o;
 4
 5    if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.null[c->resp])) == NULL)
 6        return C_OK;
 7
 8    if (o->type != OBJ_STRING) {
 9        addReply(c,shared.wrongtypeerr);
10        return C_ERR;
11    } else {
12        addReplyBulk(c,o);
13        return C_OK;
14    }
15}

lookupKeyReadOrReply()用来查找指定key存储的内容。并返回一个Redis对象,它的实现在db.c文件中。

1robj *lookupKeyReadOrReply(client *c, robj *key, robj *reply) {
2    robj *o = lookupKeyRead(c->db, key);
3    if (!o) addReply(c,reply);
4    return o;
5}

在lookupKeyReadWithFlags函数中,会先判断这个key是否过期,如果没有过期,则会继续调用lookupKey()函数进行查找。

 1robj *lookupKey(redisDb *db, robj *key, int flags) {
 2    dictEntry *de = dictFind(db->dict,key->ptr);
 3    if (de) {
 4        robj *val = dictGetVal(de);
 5
 6        /* Update the access time for the ageing algorithm.
 7         * Don't do it if we have a saving child, as this will trigger
 8         * a copy on write madness. */
 9        if (server.rdb_child_pid == -1 &&
10            server.aof_child_pid == -1 &&
11            !(flags & LOOKUP_NOTOUCH))
12        {
13            if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
14                updateLFU(val);
15            } else {
16                val->lru = LRU_CLOCK();
17            }
18        }
19        return val;
20    } else {
21        return NULL;
22    }
23}

在这个函数中,先调用了dictFind函数,找到key对应的entry,然后再从entry中取出val。

找到val后,我们回到getGenericCommand函数中,它会调用addReplyBulk函数,将返回值添加到client结构的buf字段。

1(gdb) p c->buf
2$18 = "$3\r\nzhe\r\n\n$8\r\nflushall\r\n:-1\r\n", '\000' <repeats 16354 times>

到这里,get命令的处理过程已经完结了,剩下的事情就是将结果返回给客户端,并且等待下次命令。

客户端收到返回值后,如果是控制台输出,则会调用cliFormatReplyTTY对结果进行解析

1(gdb) n
2912                    out = cliFormatReplyTTY(reply,"");
3(gdb) n
4918            fwrite(out,sdslen(out),1,stdout);
5(gdb) p out
6$5 = (sds) 0x6949b3 "\"zhe\"\n"

最后将结果输出。

参考More Redis internals: Tracing a GET & SET( 阅读原文 查看)

More Redis internals: Tracing a GET & SET


以上所述就是小编给大家介绍的《走近源码:Redis 命令执行过程(客户端)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

再启动

再启动

[日] 大前研一 / 田龙姬、金枫 / 中华工商联合出版社有限责任公司 / 2010-1 / 29.00元

1、“全球管理大师”、“日本战略之父”大前研一,职场励志最新巨作。 2、2010年1月中华工商联合出版社有限责任公司与日知公司继《货币战争2》《中国大趋势》之后,再度联手,重磅推出。 3、震撼中国职场的宗师级巨作,势必引领2010年中国职场4、世界著名出版商小学馆授予独家中文简体出版权。 5、试问,哪个老板不希望自己的员工不断实现自身的“再启动”呢? 6、只有不断激励鞭策自......一起来看看 《再启动》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

URL 编码/解码
URL 编码/解码

URL 编码/解码

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具