Redis网络模型的源码分析

Redis的网络模型是基于I/O多路复用程序来实现的。源码中包含四种多路复用函数库epoll、select、evport、kqueue。在程序编译时会根据系统自动选择这四种库其中之一。下面以epoll为例,来分析Redis的I/O模块的源码。

epoll系统调用方法

Redis网络事件处理模块的代码都是围绕epoll那三个系统方法来写的。先把这三个方法弄清楚,后面就不难了。

epfd = epoll_create(1024);

创建epoll实例
参数:表示该 epoll 实例最多可监听的 socket fd(文件描述符)数量。
返回: epoll 专用的文件描述符。

int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event)

管理epoll中的事件,对事件进行注册、修改和删除。

1参数: 2epfd:epoll实例的文件描述符; 3op:取值三种:EPOLL_CTL_ADD 注册、EPOLL_CTL_MOD 修 改、EPOLL_CTL_DEL 删除; 4fd:socket的文件描述符; 5epoll_event *event:事件

event代表一个事件,类似于Java NIO中的channel“通道”。epoll_event 的结构如下:

1typedef union epoll_data { 2void *ptr; 3int fd; /* socket文件描述符 */ 4__uint32_t u32; 5__uint64_t u64; 6} epoll_data_t; 7 8struct epoll_event { 9__uint32_t events; /* Epoll events 就是各种待监听操作的操作码求与的结果,例如EPOLLIN(fd可读)、EPOLLOUT(fd可写) */ 10epoll_data_t data; /* User data variable */ 11};

int epoll_wait(int epfd, struct epoll_event * events, intmaxevents, int timeout);

等待事件是否就绪,类似于Java NIO中 select 方法。如果事件就绪,将就绪的event存入events数组中。

1参数 2epfd:epoll实例的文件描述符; 3events:已就绪的事件数组; 4intmaxevents:每次能处理的事件数; 5timeout:阻塞时间,等待产生就绪事件的超时值。

源码分析

事件

Redis事件系统中将事件分为两种类型:

  • 文件事件;网络套接字对应的事件;
  • 时间事件:Redis中一些定时操作事件,例如 serverCron 函数。

下面从事件的注册、触发两个流程对源码进行分析

绑定事件

建立 eventLoop

在 initServer方法(由 redis.c 的 main 函数调用) 中,在建立 RedisDb 对象的同时,会初始化一个“eventLoop”对象,我称之为事件处理器对象。结构体的关键成员变量如下所示:

1struct aeEventLoop{ 2aeFileEvent *events;//已注册的文件事件数组 3aeFiredEvent *fired;//已就绪的文件事件数组 4aeTimeEvent *timeEventHead;//时间事件数组 5... 6

初始化 eventLoop 在 ae.c 的“aeCreateEventLoop”方法中执行。该方法中除了初始化 eventLoop 还调用如下方法初始化了一个 epoll 实例。

1/* 2 * ae_epoll.c 3 * 创建一个新的 epoll 实例,并将它赋值给 eventLoop 4 */ 5static int aeApiCreate(aeEventLoop *eventLoop) { 6 7 aeApiState *state = zmalloc(sizeof(aeApiState)); 8 9 if (!state) return -1; 10 11 // 初始化事件槽空间 12 state->events = zmalloc(sizeof(struct epoll_event)*eventLoop->setsize); 13 if (!state->events) { 14 zfree(state); 15 return -1; 16 } 17 18 // 创建 epoll 实例 19 state->epfd = epoll_create(1024); /* 1024 is just a hint for the kernel */ 20 if (state->epfd == -1) { 21 zfree(state->events); 22 zfree(state); 23 return -1; 24 } 25 26 // 赋值给 eventLoop 27 eventLoop->apidata = state; 28 return 0; 29}

也正是在此处调用了系统方法“epoll_create”。这里的state是一个aeApiState结构,如下所示:

1/* 2 * 事件状态 3 */ 4typedef struct aeApiState { 5 6 // epoll 实例描述符 7 int epfd; 8 9 // 事件槽 10 struct epoll_event *events; 11 12} aeApiState;

这个 state 由 eventLoop->apidata 来记录。

绑定ip端口与句柄

通过 listenToPort 方法开启TCP端口,每个IP端口会对应一个文件描述符 ipfd(因为服务器可能会有多个ip地址)

1// 打开 TCP 监听端口,用于等待客户端的命令请求 2if (server.port != 0 && 3 listenToPort(server.port,server.ipfd,&server.ipfd_count) == REDIS_ERR) 4 exit(1);

注意:*eventLoop 和 ipfd 分别被 server.el 和 server.ipfd[] 引用。server 是结构体 RedisServer 的实例,是Redis的全局变量。

注册事件

如下所示代码,为每一个文件描述符绑定一个事件函数

1// initServer方法: 2for (j = 0; j < server.ipfd_count; j++) { 3 if (aeCreateFileEvent(server.el, server.ipfd[j], AE_READABLE, 4 acceptTcpHandler,NULL) == AE_ERR) 5 { 6 redisPanic( 7 "Unrecoverable error creating server.ipfd file event."); 8 } 9} 10// ae.c 中的 aeCreateFileEvent 方法 11/* 12 * 根据 mask 参数的值,监听 fd 文件的状态, 13 * 当 fd 可用时,执行 proc 函数 14 */ 15int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask, 16 aeFileProc *proc, void *clientData) 17{ 18 if (fd >= eventLoop->setsize) { 19 errno = ERANGE; 20 return AE_ERR; 21 } 22 23 if (fd >= eventLoop->setsize) return AE_ERR; 24 25 // 取出文件事件结构 26 aeFileEvent *fe = &eventLoop->events[fd]; 27 28 // 监听指定 fd 的指定事件 29 if (aeApiAddEvent(eventLoop, fd, mask) == -1) 30 return AE_ERR; 31 32 // 设置文件事件类型,以及事件的处理器 33 fe->mask |= mask; 34 if (mask & AE_READABLE) fe->rfileProc = proc; 35 if (mask & AE_WRITABLE) fe->wfileProc = proc; 36 37 // 私有数据 38 fe->clientData = clientData; 39 40 // 如果有需要,更新事件处理器的最大 fd 41 if (fd > eventLoop->maxfd) 42 eventLoop->maxfd = fd; 43 44 return AE_OK; 45}

aeCreateFileEvent 函数中有一个方法调用:aeApiAddEvent,代码如下

1/* 2 * ae_epoll.c 3 * 关联给定事件到 fd 4 */ 5static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { 6 aeApiState *state = eventLoop->apidata; 7 struct epoll_event ee; 8 9 /* If the fd was already monitored for some event, we need a MOD 10 * operation. Otherwise we need an ADD operation. 11 * 12 * 如果 fd 没有关联任何事件,那么这是一个 ADD 操作。 13 * 14 * 如果已经关联了某个/某些事件,那么这是一个 MOD 操作。 15 */ 16 int op = eventLoop->events[fd].mask == AE_NONE ? 17 EPOLL_CTL_ADD : EPOLL_CTL_MOD; 18 19 // 注册事件到 epoll 20 ee.events = 0; 21 mask |= eventLoop->events[fd].mask; /* Merge old events */ 22 if (mask & AE_READABLE) ee.events |= EPOLLIN; 23 if (mask & AE_WRITABLE) ee.events |= EPOLLOUT; 24 ee.data.u64 = 0; /* avoid valgrind warning */ 25 ee.data.fd = fd; 26 27 if (epoll_ctl(state->epfd,op,fd,&ee) == -1) return -1; 28 29 return 0; 30}

这里实际上就是调用系统方法“epoll_ctl”,将事件(文件描述符)注册进 epoll 中。首先要封装一个 epoll_event 结构,即 ee ,通过“epoll_ctl”将其注册进 epoll 中。
除此之外,aeCreateFileEvent 还完成了下面两个重要操作:

  • 将事件函数“acceptTcpHandler”存入了eventLoop中,即由eventLoop->events[fd]->rfileProc 来引用(也可能是wfileProc,分别代表读事件和写事件);
  • 将当操作码添加进 eventLoop->events[fd]->mask 中(mask 类似于JavaNIO中的ops操作码,代表事件类型)。

事件监听与执行

redis.c 的main函数会调用 ae.c 中的 main 方法,如下所示:

1/* 2 * 事件处理器的主循环 3 */ 4void aeMain(aeEventLoop *eventLoop) { 5 6 eventLoop->stop = 0; 7 8 while (!eventLoop->stop) { 9 10 // 如果有需要在事件处理前执行的函数,那么运行它 11 if (eventLoop->beforesleep != NULL) 12 eventLoop->beforesleep(eventLoop); 13 14 // 开始处理事件 15 aeProcessEvents(eventLoop, AE_ALL_EVENTS); 16 } 17}

上述代码会调用 aeProcessEvents 方法用于处理事件,方法如下所示

1/* Process every pending time event, then every pending file event 2 * (that may be registered by time event callbacks just processed). 3 * 4 * 处理所有已到达的时间事件,以及所有已就绪的文件事件。 5 * 函数的返回值为已处理事件的数量 6 */ 7 int aeProcessEvents(aeEventLoop *eventLoop, int flags) 8{ 9 int processed = 0, numevents; 10 11 /* Nothing to do? return ASAP */ 12 if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0; 13 14 if (eventLoop->maxfd != -1 || 15 ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) { 16 int j; 17 aeTimeEvent *shortest = NULL; 18 struct timeval tv, *tvp; 19 20 // 获取最近的时间事件 21 if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT)) 22 shortest = aeSearchNearestTimer(eventLoop); 23 if (shortest) { 24 // 如果时间事件存在的话 25 // 那么根据最近可执行时间事件和现在时间的时间差来决定文件事件的阻塞时间 26 long now_sec, now_ms; 27 28 /* Calculate the time missing for the nearest 29 * timer to fire. */ 30 // 计算距今最近的时间事件还要多久才能达到 31 // 并将该时间距保存在 tv 结构中 32 aeGetTime(&now_sec, &now_ms); 33 tvp = &tv; 34 tvp->tv_sec = shortest->when_sec - now_sec; 35 if (shortest->when_ms < now_ms) { 36 tvp->tv_usec = ((shortest->when_ms+1000) - now_ms)*1000; 37 tvp->tv_sec --; 38 } else { 39 tvp->tv_usec = (shortest->when_ms - now_ms)*1000; 40 } 41 42 // 时间差小于 0 ,说明事件已经可以执行了,将秒和毫秒设为 0 (不阻塞) 43 if (tvp->tv_sec < 0) tvp->tv_sec = 0; 44 if (tvp->tv_usec < 0) tvp->tv_usec = 0; 45 } else { 46 47 // 执行到这一步,说明没有时间事件 48 // 那么根据 AE_DONT_WAIT 是否设置来决定是否阻塞,以及阻塞的时间长度 49 50 /* If we have to check for events but need to return 51 * ASAP because of AE_DONT_WAIT we need to set the timeout 52 * to zero */ 53 if (flags & AE_DONT_WAIT) { 54 // 设置文件事件不阻塞 55 tv.tv_sec = tv.tv_usec = 0; 56 tvp = &tv; 57 } else { 58 /* Otherwise we can block */ 59 // 文件事件可以阻塞直到有事件到达为止 60 tvp = NULL; /* wait forever */ 61 } 62 } 63 64 // 处理文件事件,阻塞时间由 tvp 决定 65 numevents = aeApiPoll(eventLoop, tvp); 66 for (j = 0; j < numevents; j++) { 67 // 从已就绪数组中获取事件 68 aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd]; 69 70 int mask = eventLoop->fired[j].mask; 71 int fd = eventLoop->fired[j].fd; 72 int rfired = 0; 73 74 /* note the fe->mask & mask & ... code: maybe an already processed 75 * event removed an element that fired and we still didn't 76 * processed, so we check if the event is still valid. */ 77 // 读事件 78 if (fe->mask & mask & AE_READABLE) { 79 // rfired 确保读/写事件只能执行其中一个 80 rfired = 1; 81 fe->rfileProc(eventLoop,fd,fe->clientData,mask); 82 } 83 // 写事件 84 if (fe->mask & mask & AE_WRITABLE) { 85 if (!rfired || fe->wfileProc != fe->rfileProc) 86 fe->wfileProc(eventLoop,fd,fe->clientData,mask); 87 } 88 89 processed++; 90 } 91 } 92 93 /* Check time events */ 94 // 执行时间事件 95 if (flags & AE_TIME_EVENTS) 96 processed += processTimeEvents(eventLoop); 97 98 return processed; 99}

该函数中代码大致分为三个主要步骤

  • 根据时间事件与当前时间的关系,决定阻塞时间 tvp;
  • 调用aeApiPoll方法,将就绪事件都写入eventLoop->fired[]中,返回就绪事件数目;
  • 遍历eventLoop->fired[],遍历每一个就绪事件,执行之前绑定好的方法rfileProc 或者wfileProc。

ae_epoll.c 中的 aeApiPoll 方法如下所示:

1/* 2 * 获取可执行事件 3 */ 4static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { 5 aeApiState *state = eventLoop->apidata; 6 int retval, numevents = 0; 7 8 // 等待时间 9 retval = epoll_wait(state->epfd,state->events,eventLoop->setsize, 10 tvp ? (tvp->tv_sec*1000 + tvp->tv_usec/1000) : -1); 11 12 // 有至少一个事件就绪? 13 if (retval > 0) { 14 int j; 15 16 // 为已就绪事件设置相应的模式 17 // 并加入到 eventLoop 的 fired 数组中 18 numevents = retval; 19 for (j = 0; j < numevents; j++) { 20 int mask = 0; 21 struct epoll_event *e = state->events+j; 22 23 if (e->events & EPOLLIN) mask |= AE_READABLE; 24 if (e->events & EPOLLOUT) mask |= AE_WRITABLE; 25 if (e->events & EPOLLERR) mask |= AE_WRITABLE; 26 if (e->events & EPOLLHUP) mask |= AE_WRITABLE; 27 28 eventLoop->fired[j].fd = e->data.fd; 29 eventLoop->fired[j].mask = mask; 30 } 31 } 32 33 // 返回已就绪事件个数 34 return numevents; 35}

执行epoll_wait后,就绪的事件会被写入 eventLoop->apidata->events 事件槽。后面的循环就是将事件槽中的事件写入到 eventLoop->fired[] 中。具体描述:每一个事件都是一个 epoll_event 结构,用e来指代,则e.data.fd代表文件描述符,e->events表示其操作码,将操作码转化为mask,最后将fd 和 mask 都写入eventLoop->fired[j]中。

之后,在外层的 aeProcessEvents 方法中会执行函数指针 rfileProc 或者 wfileProc 指向的方法,例如前文提到已注册的“acceptTcpHandler”。

总结

Redis的网络模块其实是一个简易的Reactor模式。本文顺着“服务端注册事件——>接受客户端连接——>监听事件是否就绪——>执行事件”这样的路线,来分析Redis源码,描述了Redis接受客户端connect的过程。实际上NIO的思想都基本类似。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )