淺析Redis與IO多路復用器原理


為什么Redis使用多路復用I/O

Redis 是跑在單線程中的,所有的操作都是按照順序線性執行的,但是由於讀寫操作等待用戶輸入或輸出都是阻塞的,所以 I/O 操作在一般情況下往往不能直接返回,這會導致某一文件的 I/O 阻塞導致整個進程無法對其它客戶提供服務,而 I/O 多路復用就是為了解決這個問題而出現的。

多路復用與傳統阻塞IO的區別

在傳統阻塞 I/O 模型中,如果對某一個文件描述符(File Descriptor ,FD)進行 readwrite 時,如果當前 FD 不可讀或不可寫,那么就會一直等待着Kernel進行數據准備,通常是從磁盤后者網卡讀入到內核態,然后Redis進行讀取,這整個過程中, Redis 服務就不會對其它的操作作出響應,一直在等待Kernel准備數據,導致整個服務不可用。

I/O 多路復用

阻塞式的 I/O 模型並不能滿足這里的需求,尋思尋思,Redis就一個線程,要是使用阻塞IO,那效率得多低,我們需要一種效率更高的 I/O 模型來支撐 Redis 的單線程應對多個客戶(redis-cli),這里涉及的就是 I/O 多路復用模型了:

在 I/O 多路復用模型中,最重要的函數調用就是 select,該方法的能夠同時監控多個文件描述符的可讀可寫情況,當其中的某些文件描述符可讀或者可寫時,select 方法就會返回可讀以及可寫的文件描述符個數。

在后期,有一些其他的多路復用函數,例如PollEpoll

關於SelectPollEpoll的區別,可以參考:多路復用器Select、Poll、Epoll區別梳理

I/O 多路復用模塊

I/O 多路復用模塊封裝了底層的 selectPollepollavport 以及 kqueue 這些 I/O 多路復用函數,為上層提供了相同的接口。

在這里我們簡單介紹 Redis 是如何包裝 selectepoll 的,簡要了解該模塊的功能,整個 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 來存儲需要的上下文信息:

// select
typedef struct aeApiState {
    fd_set rfds, wfds;
    fd_set _rfds, _wfds;
} aeApiState;

// epoll
typedef struct aeApiState {
    int epfd;
    struct epoll_event *events;
} aeApiState;

這些上下文信息會存儲在 eventLoopvoid *state 中,不會暴露到上層,只在當前子模塊中使用。

封裝 select 函數

select 可以監控 FD 的可讀、可寫以及出現錯誤的情況。

在介紹 I/O 多路復用模塊如何對 select 函數封裝之前,先來看一下 select 函數使用的大致流程:

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 */
    }
}
  1. 初始化一個可讀的 fd_set 集合,保存需要監控可讀性的 FD;
  2. 使用 FD_SETfd 加入 rfds
  3. 調用 select 方法監控 rfds 中的 FD 是否可讀;
  4. select 返回時,檢查 FD 的狀態並完成對應的操作。

而在 Redis 的 ae_select 文件中代碼的組織順序也是差不多的,首先在 aeApiCreate 函數中初始化 rfdswfds

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;
}

aeApiAddEventaeApiDelEvent 會通過 FD_SETFD_CLR 修改 fd_set 中對應 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 子模塊中最重要的函數就是 aeApiPoll,它是實際調用 select 函數的部分,其作用就是在 I/O 多路復用函數返回時,將對應的 FD 加入 aeEventLoopfired 數組中,並返回事件的個數:

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 函數

Redis 對 epoll 的封裝其實也是類似的,使用 epoll_create 創建 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_ctlepfd 中添加需要監控的 FD 以及監聽的事件:

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 函數返回時並不需要遍歷所有的 FD 查看讀寫情況;在 epoll_wait 函數返回時會提供一個 epoll_event 數組:

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;
};

其中保存了發生的 epoll 事件(EPOLLINEPOLLOUTEPOLLERREPOLLHUP)以及發生該事件的 FD。

aeApiPoll 函數只需要將 epoll_event 數組中存儲的信息加入 eventLoopfired 數組中,將信息傳遞給上層模塊:

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 需要在多個平台上運行,同時為了最大化執行的效率與性能,所以會根據編譯平台的不同選擇不同的 I/O 多路復用函數作為子模塊,提供給上層統一的接口;在 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 函數是作為 POSIX 標准中的系統調用,在不同版本的操作系統上都會實現,所以將其作為保底方案:

Redis 會優先選擇時間復雜度為 \(O(1)\) 的 I/O 多路復用函數作為底層實現,包括 Solaries 10 中的 evport、Linux 中的 epoll 和 macOS/FreeBSD 中的 kqueue,上述的這些函數都使用了內核內部的結構,並且能夠服務幾十萬的文件描述符。

但是如果當前編譯環境沒有上述函數,就會選擇 select 作為備選方案,由於其在使用時會掃描全部監聽的描述符,所以其時間復雜度較差 \(O(n)\),並且只能同時服務 1024 個文件描述符,所以一般並不會以 select 作為第一方案使用。

總結

Redis 對於 I/O 多路復用模塊的設計非常簡潔,通過宏保證了 I/O 多路復用模塊在不同平台上都有着優異的性能,將不同的 I/O 多路復用函數封裝成相同的 API 提供給上層使用。

整個模塊使 Redis 能以單進程運行的同時服務成千上萬個文件描述符,避免了由於多進程應用的引入導致代碼實現復雜度的提升,減少了出錯的可能性。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM