电竞比分网-中国电竞赛事及体育赛事平台

分享

為什么 Redis 單線程能支撐高并發(fā)?

 caiyong1987 2019-06-12

作者:Draveness

https:///redis-io-multiplexing

最近在看 UNIX 網(wǎng)絡(luò)編程并研究了一下 Redis 的實現(xiàn),感覺 Redis 的源代碼十分適合閱讀和分析,其中 I/O 多路復(fù)用(mutiplexing)部分的實現(xiàn)非常干凈和優(yōu)雅,在這里想對這部分的內(nèi)容進(jìn)行簡單的整理。

幾種 I/O 模型

為什么 Redis 中要使用 I/O 多路復(fù)用這種技術(shù)呢?

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

Blocking I/O

先來看一下傳統(tǒng)的阻塞 I/O 模型到底是如何工作的:當(dāng)使用 read 或者 write 對某一個文件描述符(File Descriptor 以下簡稱 FD)進(jìn)行讀寫時,如果當(dāng)前 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)控多個文件描述符的可讀可寫情況,當(dāng)其中的某些文件描述符可讀或者可寫時,select 方法就會返回可讀以及可寫的文件描述符個數(shù)。

關(guān)于 select 的具體使用方法,在網(wǎng)絡(luò)上資料很多,這里就不過多展開介紹了;

與此同時也有其它的 I/O 多路復(fù)用函數(shù) epoll/kqueue/evport,它們相比 select 性能更優(yōu)秀,同時也能支撐更多的服務(wù)。詳解 Java 中 4 種 I/O 模型,這篇文章可以參考下。

Reactor 設(shè)計模式

Redis 服務(wù)采用 Reactor 的方式來實現(xiàn)文件事件處理器(每一個網(wǎng)絡(luò)連接其實都對應(yīng)一個文件描述符)

文件事件處理器使用 I/O 多路復(fù)用模塊同時監(jiān)聽多個 FD,當(dāng) 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 中,不會暴露到上層,只在當(dāng)前子模塊中使用。

封裝 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, NULLNULLNULL);
    if (FD_ISSET(fd, &rfds)) {
        /* file descriptor `fd` becomes readable */
    }
}
  • 初始化一個可讀的 fd_set 集合,保存需要監(jiān)控可讀性的 FD;

  • 使用 FD_SET 將 fd 加入 rfds;

  • 調(diào)用 select 方法監(jiān)控 rfds 中的 FD 是否可讀;

  • 當(dāng) select 返回時,檢查 FD 的狀態(tài)并完成對應(yīng)的操作。

而在 Redis 的 ae_select 文件中代碼的組織順序也是差不多的,首先在 aeApiCreate 函數(shù)中初始化 rfds 和 wfds:

static int aeApiCreate(aeEventLoop *eventLoop) {
    aeApiState *state = zmalloc(sizeof(aeApiState));
    if (!statereturn -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 的標(biāo)志位:

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) == -1return -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 標(biāo)準(zhǔn)中的系統(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ù)幾十萬的文件描述符。

但是如果當(dāng)前編譯環(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 能以單進(jìn)程運行的同時服務(wù)成千上萬個文件描述符,避免了由于多進(jìn)程應(yīng)用的引入導(dǎo)致代碼實現(xiàn)復(fù)雜度的提升,減少了出錯的可能性。

參考

http:///linux/man-pages/man2/select.2.html
https://en./wiki/Reactor_pattern
https://people.eecs./~sangjin/2012/12/21/epoll-vs-kqueue.html

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多