redis的socket event loop

很早之前就因为nosql就听说了redis,直到去年才真正去了解,只能说相见恨晚。

因为数据库相关,我以为这应该是个庞然大物,万万没想到,源码不到2M,所以,我不知道该说啥了。。。

还是来点靠谱的:

 1 /* Include the best multiplexing layer supported by this system.
 2  * The following should be ordered by performances, descending. */
 3 #ifdef HAVE_EVPORT
 4 #include "ae_evport.c"
 5 #else
 6     #ifdef HAVE_EPOLL
 7     #include "ae_epoll.c"
 8     #else
 9         #ifdef HAVE_KQUEUE
10         #include "ae_kqueue.c"
11         #else
12         #include "ae_select.c"
13         #endif
14     #endif
15 #endif

按照redis作者的排位,从上到下,性能是递减的,也就是evport>epoll>kqueue>select。libevent库上面有个benchmark,可能比较权威,http://libevent.org/ (那破图我能说点什么吗)

这个排位估计众说纷纭,对我来说,够用就好。

下面是redis定义的事件轮询函数原型:

 1 /* Prototypes */
 2 aeEventLoop *aeCreateEventLoop(int setsize);
 3 void aeDeleteEventLoop(aeEventLoop *eventLoop);
 4 void aeStop(aeEventLoop *eventLoop);
 5 int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask,
 6         aeFileProc *proc, void *clientData);
 7 void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask);
 8 int aeGetFileEvents(aeEventLoop *eventLoop, int fd);
 9 long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds,
10         aeTimeProc *proc, void *clientData,
11         aeEventFinalizerProc *finalizerProc);
12 int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id);
13 int aeProcessEvents(aeEventLoop *eventLoop, int flags);
14 int aeWait(int fd, int mask, long long milliseconds);
15 void aeMain(aeEventLoop *eventLoop);
16 char *aeGetApiName(void);
17 void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep);
18 int aeGetSetSize(aeEventLoop *eventLoop);
19 int aeResizeSetSize(aeEventLoop *eventLoop, int setsize);

看到这个让我想起了大概是2007年微软推出mvc三层架构里的数据库访问层,封装各类数据库api,来实现一个抽象统一的数据访问中间层,

那么,在这里对不同socket IO复用实现也进行了统一的封装。或者很类似设计模式里的bridge模式。

多的我也不说了,参考大神的博客:

http://www.kegel.com/c10k.html

http://pl.atyp.us/content/tech/servers.html

原文地址:https://www.cnblogs.com/danxi/p/6404082.html