Redis 和 I/O 多路复用
最近在看 UNIX 網(wǎng)絡(luò)編程并研究了一下 Redis 的實現(xiàn),感覺 Redis 的源代碼十分適合閱讀和分析,其中 I/O 多路復(fù)用(mutiplexing)部分的實現(xiàn)非常干凈和優(yōu)雅,在這里想對這部分的內(nèi)容進行簡單的整理。
幾種 I/O 模型
為什么 Redis 中要使用 I/O 多路復(fù)用這種技術(shù)呢?
首先,Redis 是跑在單線程中的,所有的操作都是按照順序線性執(zhí)行的,但是由于讀寫操作等待用戶輸入或輸出都是阻塞的,所以 I/O 操作在一般情況下往往不能直接返回,這會導(dǎo)致某一文件的 I/O 阻塞導(dǎo)致整個進程無法對其它客戶提供服務(wù),而?I/O 多路復(fù)用就是為了解決這個問題而出現(xiàn)的。
Blocking I/O
先來看一下傳統(tǒng)的阻塞 I/O 模型到底是如何工作的:當使用?read?或者?write?對某一個文件描述符(File Descriptor 以下簡稱 FD)進行讀寫時,如果當前 FD 不可讀或不可寫,整個 Redis 服務(wù)就不會對其它的操作作出響應(yīng),導(dǎo)致整個服務(wù)不可用。
這也就是傳統(tǒng)意義上的,也就是我們在編程中使用最多的阻塞模型:
阻塞模型雖然開發(fā)中非常常見也非常易于理解,但是由于它會影響其他 FD 對應(yīng)的服務(wù),所以在需要處理多個客戶端任務(wù)的時候,往往都不會使用阻塞模型。
I/O 多路復(fù)用
雖然還有很多其它的 I/O 模型,但是在這里都不會具體介紹。
阻塞式的 I/O 模型并不能滿足這里的需求,我們需要一種效率更高的 I/O 模型來支撐 Redis 的多個客戶(redis-cli),這里涉及的就是 I/O 多路復(fù)用模型了:
在 I/O 多路復(fù)用模型中,最重要的函數(shù)調(diào)用就是?select,該方法的能夠同時監(jiān)控多個文件描述符的可讀可寫情況,當其中的某些文件描述符可讀或者可寫時,select?方法就會返回可讀以及可寫的文件描述符個數(shù)。
關(guān)于?select?的具體使用方法,在網(wǎng)絡(luò)上資料很多,這里就不過多展開介紹了;
與此同時也有其它的 I/O 多路復(fù)用函數(shù)?epoll/kqueue/evport,它們相比?select?性能更優(yōu)秀,同時也能支撐更多的服務(wù)。
Reactor 設(shè)計模式
Redis 服務(wù)采用 Reactor 的方式來實現(xiàn)文件事件處理器(每一個網(wǎng)絡(luò)連接其實都對應(yīng)一個文件描述符)
文件事件處理器使用 I/O 多路復(fù)用模塊同時監(jiān)聽多個 FD,當?accept、read、write?和?close?文件事件產(chǎn)生時,文件事件處理器就會回調(diào) FD 綁定的事件處理器。
雖然整個文件事件處理器是在單線程上運行的,但是通過 I/O 多路復(fù)用模塊的引入,實現(xiàn)了同時對多個 FD 讀寫的監(jiān)控,提高了網(wǎng)絡(luò)通信模型的性能,同時也可以保證整個 Redis 服務(wù)實現(xiàn)的簡單。
I/O 多路復(fù)用模塊
I/O 多路復(fù)用模塊封裝了底層的?select、epoll、avport?以及?kqueue?這些 I/O 多路復(fù)用函數(shù),為上層提供了相同的接口。
在這里我們簡單介紹 Redis 是如何包裝?select?和?epoll?的,簡要了解該模塊的功能,整個 I/O 多路復(fù)用模塊抹平了不同平臺上 I/O 多路復(fù)用函數(shù)的差異性,提供了相同的接口:
- 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)
同時,因為各個函數(shù)所需要的參數(shù)不同,我們在每一個子模塊內(nèi)部通過一個?aeApiState?來存儲需要的上下文信息:
// select typedef struct aeApiState {fd_set rfds, wfds;fd_set _rfds, _wfds; } aeApiState;// epoll typedef struct aeApiState {int epfd;struct epoll_event *events; } aeApiState;這些上下文信息會存儲在?eventLoop?的?void *state?中,不會暴露到上層,只在當前子模塊中使用。
封裝 select 函數(shù)
select?可以監(jiān)控 FD 的可讀、可寫以及出現(xiàn)錯誤的情況。
在介紹 I/O 多路復(fù)用模塊如何對?select?函數(shù)封裝之前,先來看一下?select?函數(shù)使用的大致流程:
int fd = /* file descriptor */fd_set rfds; FD_ZERO(&rfds); FD_SET(fd, &rfds)for ( ; ; ) {select(fd+1, &rfds, NULL, NULL, NULL);if (FD_ISSET(fd, &rfds)) {/* file descriptor `fd` becomes readable */} }而在 Redis 的?ae_select?文件中代碼的組織順序也是差不多的,首先在?aeApiCreate?函數(shù)中初始化?rfds?和?wfds:
static int aeApiCreate(aeEventLoop *eventLoop) {aeApiState *state = zmalloc(sizeof(aeApiState));if (!state) return -1;FD_ZERO(&state->rfds);FD_ZERO(&state->wfds);eventLoop->apidata = state;return 0; }而?aeApiAddEvent?和?aeApiDelEvent?會通過?FD_SET?和?FD_CLR?修改?fd_set?中對應(yīng) FD 的標志位:
static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) {aeApiState *state = eventLoop->apidata;if (mask & AE_READABLE) FD_SET(fd,&state->rfds);if (mask & AE_WRITABLE) FD_SET(fd,&state->wfds);return 0; }整個?ae_select?子模塊中最重要的函數(shù)就是?aeApiPoll,它是實際調(diào)用?select?函數(shù)的部分,其作用就是在 I/O 多路復(fù)用函數(shù)返回時,將對應(yīng)的 FD 加入?aeEventLoop?的?fired?數(shù)組中,并返回事件的個數(shù):
static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) {aeApiState *state = eventLoop->apidata;int retval, j, numevents = 0;memcpy(&state->_rfds,&state->rfds,sizeof(fd_set));memcpy(&state->_wfds,&state->wfds,sizeof(fd_set));retval = select(eventLoop->maxfd+1,&state->_rfds,&state->_wfds,NULL,tvp);if (retval > 0) {for (j = 0; j <= eventLoop->maxfd; j++) {int mask = 0;aeFileEvent *fe = &eventLoop->events[j];if (fe->mask == AE_NONE) continue;if (fe->mask & AE_READABLE && FD_ISSET(j,&state->_rfds))mask |= AE_READABLE;if (fe->mask & AE_WRITABLE && FD_ISSET(j,&state->_wfds))mask |= AE_WRITABLE;eventLoop->fired[numevents].fd = j;eventLoop->fired[numevents].mask = mask;numevents++;}}return numevents; }封裝 epoll 函數(shù)
Redis 對?epoll?的封裝其實也是類似的,使用?epoll_create?創(chuàng)建?epoll?中使用的?epfd:
static int aeApiCreate(aeEventLoop *eventLoop) {aeApiState *state = zmalloc(sizeof(aeApiState));if (!state) return -1;state->events = zmalloc(sizeof(struct epoll_event)*eventLoop->setsize);if (!state->events) {zfree(state);return -1;}state->epfd = epoll_create(1024); /* 1024 is just a hint for the kernel */if (state->epfd == -1) {zfree(state->events);zfree(state);return -1;}eventLoop->apidata = state;return 0; }在?aeApiAddEvent?中使用?epoll_ctl?向?epfd?中添加需要監(jiān)控的 FD 以及監(jiān)聽的事件:
static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) {aeApiState *state = eventLoop->apidata;struct epoll_event ee = {0}; /* avoid valgrind warning *//* If the fd was already monitored for some event, we need a MOD* operation. Otherwise we need an ADD operation. */int op = eventLoop->events[fd].mask == AE_NONE ?EPOLL_CTL_ADD : EPOLL_CTL_MOD;ee.events = 0;mask |= eventLoop->events[fd].mask; /* Merge old events */if (mask & AE_READABLE) ee.events |= EPOLLIN;if (mask & AE_WRITABLE) ee.events |= EPOLLOUT;ee.data.fd = fd;if (epoll_ctl(state->epfd,op,fd,&ee) == -1) return -1;return 0; }由于?epoll?相比?select?機制略有不同,在?epoll_wait?函數(shù)返回時并不需要遍歷所有的 FD 查看讀寫情況;在?epoll_wait?函數(shù)返回時會提供一個?epoll_event?數(shù)組:
typedef union epoll_data {void *ptr;int fd; /* 文件描述符 */uint32_t u32;uint64_t u64; } epoll_data_t;struct epoll_event {uint32_t events; /* Epoll 事件 */epoll_data_t data; };其中保存了發(fā)生的?epoll?事件(EPOLLIN、EPOLLOUT、EPOLLERR?和?EPOLLHUP)以及發(fā)生該事件的 FD。
aeApiPoll?函數(shù)只需要將?epoll_event?數(shù)組中存儲的信息加入?eventLoop?的?fired?數(shù)組中,將信息傳遞給上層模塊:
static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) {aeApiState *state = eventLoop->apidata;int retval, numevents = 0;retval = epoll_wait(state->epfd,state->events,eventLoop->setsize,tvp ? (tvp->tv_sec*1000 + tvp->tv_usec/1000) : -1);if (retval > 0) {int j;numevents = retval;for (j = 0; j < numevents; j++) {int mask = 0;struct epoll_event *e = state->events+j;if (e->events & EPOLLIN) mask |= AE_READABLE;if (e->events & EPOLLOUT) mask |= AE_WRITABLE;if (e->events & EPOLLERR) mask |= AE_WRITABLE;if (e->events & EPOLLHUP) mask |= AE_WRITABLE;eventLoop->fired[j].fd = e->data.fd;eventLoop->fired[j].mask = mask;}}return numevents; }子模塊的選擇
因為 Redis 需要在多個平臺上運行,同時為了最大化執(zhí)行的效率與性能,所以會根據(jù)編譯平臺的不同選擇不同的 I/O 多路復(fù)用函數(shù)作為子模塊,提供給上層統(tǒng)一的接口;在 Redis 中,我們通過宏定義的使用,合理的選擇不同的子模塊:
#ifdef HAVE_EVPORT #include "ae_evport.c" #else#ifdef HAVE_EPOLL#include "ae_epoll.c"#else#ifdef HAVE_KQUEUE#include "ae_kqueue.c"#else#include "ae_select.c"#endif#endif #endif因為?select?函數(shù)是作為 POSIX 標準中的系統(tǒng)調(diào)用,在不同版本的操作系統(tǒng)上都會實現(xiàn),所以將其作為保底方案:
Redis 會優(yōu)先選擇時間復(fù)雜度為 $O(1)$ 的 I/O 多路復(fù)用函數(shù)作為底層實現(xiàn),包括 Solaries 10 中的?evport、Linux 中的?epoll?和 macOS/FreeBSD 中的?kqueue,上述的這些函數(shù)都使用了內(nèi)核內(nèi)部的結(jié)構(gòu),并且能夠服務(wù)幾十萬的文件描述符。
但是如果當前編譯環(huán)境沒有上述函數(shù),就會選擇?select?作為備選方案,由于其在使用時會掃描全部監(jiān)聽的描述符,所以其時間復(fù)雜度較差 $O(n)$,并且只能同時服務(wù) 1024 個文件描述符,所以一般并不會以?select?作為第一方案使用。
總結(jié)
Redis 對于 I/O 多路復(fù)用模塊的設(shè)計非常簡潔,通過宏保證了 I/O 多路復(fù)用模塊在不同平臺上都有著優(yōu)異的性能,將不同的 I/O 多路復(fù)用函數(shù)封裝成相同的 API 提供給上層使用。
整個模塊使 Redis 能以單進程運行的同時服務(wù)成千上萬個文件描述符,避免了由于多進程應(yīng)用的引入導(dǎo)致代碼實現(xiàn)復(fù)雜度的提升,減少了出錯的可能性。
Reference
- Select-Man-Pages
- Reactor-Pattern
- epoll vs kqueue
https://draveness.me/redis-io-multiplexing
總結(jié)
以上是生活随笔為你收集整理的Redis 和 I/O 多路复用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我很懒,什么都没留下系列 之 教你上手R
- 下一篇: linux内核剖析(八)进程间通信之-管