Redis 单线程还高并发?不冲突吗?

存储 存储软件 Redis
最近在看 UNIX 网络编程并研究了一下 Redis 的实现,感觉 Redis 的源代码十分适合阅读和分析,其中 I/O 多路复用(mutiplexing)部分的实现非常干净和优雅,在这里想对这部分的内容进行简单的整理。

 几种 I/O 模型

  • Blocking I/O
  • I/O 多路复用

Reactor 设计模式

I/O 多路复用模块

  • 封装 select 函数
  • 封装 epoll 函数
  • 子模块的选择

总结

Reference

最近在看 UNIX 网络编程并研究了一下 Redis 的实现,感觉 Redis 的源代码十分适合阅读和分析,其中 I/O 多路复用(mutiplexing)部分的实现非常干净和优雅,在这里想对这部分的内容进行简单的整理。

[[283505]]

几种 I/O 模型

为什么 Redis 中要使用 I/O 多路复用这种技术呢?

首先,Redis 是跑在单线程中的,所有的操作都是按照顺序线性执行的,但是由于读写操作等待用户输入或输出都是阻塞的,所以 I/O 操作在一般情况下往往不能直接返回,这会导致某一文件的 I/O 阻塞导致整个进程无法对其它客户提供服务,而 I/O 多路复用就是为了解决这个问题而出现的。

Blocking I/O

先来看一下传统的阻塞 I/O 模型到底是如何工作的:当使用 read 或者 write 对某一个文件描述符(File Descriptor 以下简称 FD)进行读写时,如果当前 FD 不可读或不可写,整个 Redis 服务就不会对其它的操作作出响应,导致整个服务不可用。

这也就是传统意义上的,也就是我们在编程中使用最多的阻塞模型:

blocking-io

 

阻塞模型虽然开发中非常常见也非常易于理解,但是由于它会影响其他 FD 对应的服务,所以在需要处理多个客户端任务的时候,往往都不会使用阻塞模型。

I/O 多路复用

虽然还有很多其它的 I/O 模型,但是在这里都不会具体介绍。

阻塞式的 I/O 模型并不能满足这里的需求,我们需要一种效率更高的 I/O 模型来支撑 Redis 的多个客户(redis-cli),这里涉及的就是 I/O 多路复用模型了:

I:O-Multiplexing-Mode

 

在 I/O 多路复用模型中,最重要的函数调用就是 select,该方法的能够同时监控多个文件描述符的可读可写情况,当其中的某些文件描述符可读或者可写时,select 方法就会返回可读以及可写的文件描述符个数。

关于 select 的具体使用方法,在网络上资料很多,这里就不过多展开介绍了;

与此同时也有其它的 I/O 多路复用函数 epoll/kqueue/evport,它们相比 select 性能更优秀,同时也能支撑更多的服务。

Reactor 设计模式

Redis 服务采用 Reactor 的方式来实现文件事件处理器(每一个网络连接其实都对应一个文件描述符)

redis-reactor-pattern

 

文件事件处理器使用 I/O 多路复用模块同时监听多个 FD,当 accept、read、write 和 close 文件事件产生时,文件事件处理器就会回调 FD 绑定的事件处理器。

虽然整个文件事件处理器是在单线程上运行的,但是通过 I/O 多路复用模块的引入,实现了同时对多个 FD 读写的监控,提高了网络通信模型的性能,同时也可以保证整个 Redis 服务实现的简单。

I/O 多路复用模块

I/O 多路复用模块封装了底层的 select、epoll、avport 以及 kqueue 这些 I/O 多路复用函数,为上层提供了相同的接口。

ae-module

 

在这里我们简单介绍 Redis 是如何包装 select 和 epoll 的,简要了解该模块的功能,整个 I/O 多路复用模块抹平了不同平台上 I/O 多路复用函数的差异性,提供了相同的接口:

  • static int aeApiCreate(aeEventLoop *eventLoop)
  • static int aeApiResize(aeEventLoop *eventLoop, int setsize)
  • static void aeApiFree(aeEventLoop *eventLoop)
  • static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask)
  • static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask)
  • static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp)

同时,因为各个函数所需要的参数不同,我们在每一个子模块内部通过一个 aeApiState 来存储需要的上下文信息:

  1. // select 
  2. typedef struct aeApiState { 
  3.     fd_set rfds, wfds; 
  4.     fd_set _rfds, _wfds; 
  5. } aeApiState; 
  6.  
  7. // epoll 
  8. typedef struct aeApiState { 
  9.     int epfd; 
  10.     struct epoll_event *events; 
  11. } aeApiState; 

这些上下文信息会存储在 eventLoop 的 void *state 中,不会暴露到上层,只在当前子模块中使用。

封装 select 函数

select 可以监控 FD 的可读、可写以及出现错误的情况。

在介绍 I/O 多路复用模块如何对 select 函数封装之前,先来看一下 select 函数使用的大致流程:

  1. int fd = /* file descriptor */ 
  2.  
  3. fd_set rfds; 
  4. FD_ZERO(&rfds); 
  5. FD_SET(fd, &rfds) 
  6.  
  7. for ( ; ; ) { 
  8.     select(fd+1, &rfds, NULLNULLNULL); 
  9.     if (FD_ISSET(fd, &rfds)) { 
  10.         /* file descriptor `fd` becomes readable */ 
  11.     } 
  1. 初始化一个可读的 fd_set 集合,保存需要监控可读性的 FD;
  2. 使用 FD_SET 将 fd 加入 rfds;
  3. 调用 select 方法监控 rfds 中的 FD 是否可读;
  4. 当 select 返回时,检查 FD 的状态并完成对应的操作。

而在 Redis 的 ae_select 文件中代码的组织顺序也是差不多的,首先在 aeApiCreate 函数中初始化 rfds 和 wfds:

  1. static int aeApiCreate(aeEventLoop *eventLoop) { 
  2.     aeApiState *state = zmalloc(sizeof(aeApiState)); 
  3.     if (!state) return -1; 
  4.     FD_ZERO(&state->rfds); 
  5.     FD_ZERO(&state->wfds); 
  6.     eventLoop->apidata = state; 
  7.     return 0; 

而 aeApiAddEvent 和 aeApiDelEvent 会通过 FD_SET 和 FD_CLR 修改 fd_set 中对应 FD 的标志位:

 

整个 ae_select 子模块中最重要的函数就是 aeApiPoll,它是实际调用 select 函数的部分,其作用就是在 I/O 多路复用函数返回时,将对应的 FD 加入 aeEventLoop 的 fired 数组中,并返回事件的个数:

  1. static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { 
  2.     aeApiState *state = eventLoop->apidata; 
  3.     int retval, j, numevents = 0; 
  4.  
  5.     memcpy(&state->_rfds,&state->rfds,sizeof(fd_set)); 
  6.     memcpy(&state->_wfds,&state->wfds,sizeof(fd_set)); 
  7.  
  8.     retval = select(eventLoop->maxfd+1, 
  9.                 &state->_rfds,&state->_wfds,NULL,tvp); 
  10.     if (retval > 0) { 
  11.         for (j = 0; j <= eventloop-="">maxfd; j++) { 
  12.             int mask = 0; 
  13.             aeFileEvent *fe = &eventLoop->events[j]; 
  14.  
  15.             if (fe->mask == AE_NONE) continue
  16.             if (fe->mask & AE_READABLE && FD_ISSET(j,&state->_rfds)) 
  17.                 mask |= AE_READABLE; 
  18.             if (fe->mask & AE_WRITABLE && FD_ISSET(j,&state->_wfds)) 
  19.                 mask |= AE_WRITABLE; 
  20.             eventLoop->fired[numevents].fd = j; 
  21.             eventLoop->fired[numevents].mask = mask; 
  22.             numevents++; 
  23.         } 
  24.     } 
  25.     return numevents; 

封装 epoll 函数

Redis 对 epoll 的封装其实也是类似的,使用 epoll_create 创建 epoll 中使用的 epfd:

  1. static int aeApiCreate(aeEventLoop *eventLoop) { 
  2.     aeApiState *state = zmalloc(sizeof(aeApiState)); 
  3.  
  4.     if (!state) return -1; 
  5.     state->events = zmalloc(sizeof(struct epoll_event)*eventLoop->setsize); 
  6.     if (!state->events) { 
  7.         zfree(state); 
  8.         return -1; 
  9.     } 
  10.     state->epfd = epoll_create(1024); /* 1024 is just a hint for the kernel */ 
  11.     if (state->epfd == -1) { 
  12.         zfree(state->events); 
  13.         zfree(state); 
  14.         return -1; 
  15.     } 
  16.     eventLoop->apidata = state; 
  17.     return 0; 

在 aeApiAddEvent 中使用 epoll_ctl 向 epfd 中添加需要监控的 FD 以及监听的事件:

  1. static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { 
  2.     aeApiState *state = eventLoop->apidata; 
  3.     struct epoll_event ee = {0}; /* avoid valgrind warning */ 
  4.     /* If the fd was already monitored for some event, we need a MOD 
  5.      * operation. Otherwise we need an ADD operation. */ 
  6.     int op = eventLoop->events[fd].mask == AE_NONE ? 
  7.             EPOLL_CTL_ADD : EPOLL_CTL_MOD; 
  8.  
  9.     ee.events = 0; 
  10.     mask |= eventLoop->events[fd].mask; /* Merge old events */ 
  11.     if (mask & AE_READABLE) ee.events |= EPOLLIN; 
  12.     if (mask & AE_WRITABLE) ee.events |= EPOLLOUT; 
  13.     ee.data.fd = fd; 
  14.     if (epoll_ctl(state->epfd,op,fd,&ee) == -1) return -1; 
  15.     return 0; 

由于 epoll 相比 select 机制略有不同,在 epoll_wait 函数返回时并不需要遍历所有的 FD 查看读写情况;在 epoll_wait 函数返回时会提供一个 epoll_event 数组:

  1. typedef union epoll_data { 
  2.     void    *ptr; 
  3.     int      fd; /* 文件描述符 */ 
  4.     uint32_t u32; 
  5.     uint64_t u64; 
  6. } epoll_data_t; 
  7.  
  8. struct epoll_event { 
  9.     uint32_t     events; /* Epoll 事件 */ 
  10.     epoll_data_t data; 
  11. }; 

其中保存了发生的 epoll 事件(EPOLLIN、EPOLLOUT、EPOLLERR 和 EPOLLHUP)以及发生该事件的 FD。

aeApiPoll 函数只需要将 epoll_event 数组中存储的信息加入 eventLoop 的 fired 数组中,将信息传递给上层模块:

  1. static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { 
  2.     aeApiState *state = eventLoop->apidata; 
  3.     int retval, numevents = 0; 
  4.  
  5.     retval = epoll_wait(state->epfd,state->events,eventLoop->setsize, 
  6.             tvp ? (tvp->tv_sec*1000 + tvp->tv_usec/1000) : -1); 
  7.     if (retval > 0) { 
  8.         int j; 
  9.  
  10.         numevents = retval; 
  11.         for (j = 0; j < numevents; j++) { 
  12.             int mask = 0; 
  13.             struct epoll_event *e = state->events+j; 
  14.  
  15.             if (e->events & EPOLLIN) mask |= AE_READABLE; 
  16.             if (e->events & EPOLLOUT) mask |= AE_WRITABLE; 
  17.             if (e->events & EPOLLERR) mask |= AE_WRITABLE; 
  18.             if (e->events & EPOLLHUP) mask |= AE_WRITABLE; 
  19.             eventLoop->fired[j].fd = e->data.fd; 
  20.             eventLoop->fired[j].mask = mask; 
  21.         } 
  22.     } 
  23.     return numevents; 

子模块的选择

因为 Redis 需要在多个平台上运行,同时为了最大化执行的效率与性能,所以会根据编译平台的不同选择不同的 I/O 多路复用函数作为子模块,提供给上层统一的接口;在 Redis 中,我们通过宏定义的使用,合理的选择不同的子模块:

  1. #ifdef HAVE_EVPORT 
  2. #include "ae_evport.c" 
  3. #else 
  4.     #ifdef HAVE_EPOLL 
  5.     #include "ae_epoll.c" 
  6.     #else 
  7.         #ifdef HAVE_KQUEUE 
  8.         #include "ae_kqueue.c" 
  9.         #else 
  10.         #include "ae_select.c" 
  11.         #endif 
  12.     #endif 
  13. #endif 

因为 select 函数是作为 POSIX 标准中的系统调用,在不同版本的操作系统上都会实现,所以将其作为保底方案:

redis-choose-io-function

 

 

Redis 会优先选择时间复杂度为

 


的 I/O 多路复用函数作为底层实现,包括 Solaries 10 中的 evport、Linux 中的 epoll 和 macOS/FreeBSD 中的 kqueue,上述的这些函数都使用了内核内部的结构,并且能够服务几十万的文件描述符。

 

 

但是如果当前编译环境没有上述函数,就会选择 select 作为备选方案,由于其在使用时会扫描全部监听的描述符,所以其时间复杂度较差,并且只能同时服务 1024 个文件描述符,所以一般并不会以 select 作为第一方案使用。

 

总结

Redis 对于 I/O 多路复用模块的设计非常简洁,通过宏保证了 I/O 多路复用模块在不同平台上都有着优异的性能,将不同的 I/O 多路复用函数封装成相同的 API 提供给上层使用。

整个模块使 Redis 能以单进程运行的同时服务成千上万个文件描述符,避免了由于多进程应用的引入导致代码实现复杂度的提升,减少了出错的可能性。

Reference

  • Select-Man-Pages
  • Reactor-Pattern
  • epoll vs kqueue

 

责任编辑:武晓燕 来源: 互扯程序
相关推荐

2023-12-01 08:18:24

Redis网络

2020-09-23 13:37:25

Redis6.0

2020-10-30 16:20:38

Redis单线程高并发

2019-05-06 11:12:18

Redis高并发单线程

2019-05-07 09:44:45

Redis高并发模型

2022-01-04 11:11:32

Redis单线程Reactor

2020-11-17 10:20:53

Redis多线程单线程

2009-07-10 09:05:20

SwingWorker

2021-01-10 11:21:33

JavaScript语言开发

2021-08-10 07:00:01

Redis单线程并发

2022-07-18 13:59:43

Redis单线程进程

2021-12-28 09:50:18

Redis单线程高并发

2019-06-17 14:20:51

Redis数据库Java

2020-06-11 09:35:39

Redis单线程Java

2023-10-15 12:23:10

单线程Redis

2023-08-17 14:12:17

2020-11-09 09:33:37

多线程

2023-03-21 08:02:36

Redis6.0IO多线程

2010-08-30 08:55:56

JavaScript引

2019-10-29 20:13:43

Java技术程序员
点赞
收藏

51CTO技术栈公众号