Redis源码学习之【事件机制】

来源:互联网 发布:乐视视频无法连接网络 编辑:程序博客网 时间:2024/06/16 09:58

介绍

Redis实现了自己的一套和libevent类似的事件驱动机制,主要用于处理时间事件和文件事件。文件事件底层主要是指网络IO事件的处理,底层使用的可能是select,epoll,或者是kqueue。Redis使用自己实现的AE而不是像memcache使用的libevent使得其性能更好,因为libevent为了其通用性增加了很多扩展功能显然会降低使用它的性能。

源码

ae.h ae.c

分析

总体流程



简单说来Redis使用的事件处理机制就是通过一个主aeMain循环在单线程执行,在每一次循环中首先查看是否需要有其他阻塞的客户端或者是aof需要执行。然后在具体的aeProcessEvents中则根据传递的参数判断如何处理文件事件和时间事件。具体可以参考下面的说明。

主要函数说明

aeProcessEvents

[cpp] view plaincopy
  1. /* Process every pending time event, then every pending file event 
  2.  * (that may be registered by time event callbacks just processed). 
  3.  * 
  4.  * 处理所有已到达的时间事件,以及所有已就绪的文件事件。 
  5.  * 
  6.  * Without special flags the function sleeps until some file event 
  7.  * fires, or when the next time event occurrs (if any). 
  8.  * 
  9.  * 如果不传入特殊 flags 的话,那么函数睡眠直到文件事件就绪, 
  10.  * 或者下个时间事件到达(如果有的话)。 
  11.  * 
  12.  * If flags is 0, the function does nothing and returns. 
  13.  * 如果 flags 为 0 ,那么函数不作动作,直接返回。 
  14.  * 
  15.  * if flags has AE_ALL_EVENTS set, all the kind of events are processed. 
  16.  * 如果 flags 包含 AE_ALL_EVENTS ,所有类型的事件都会被处理。 
  17.  * 
  18.  * if flags has AE_FILE_EVENTS set, file events are processed. 
  19.  * 如果 flags 包含 AE_FILE_EVENTS ,那么处理文件事件。 
  20.  * 
  21.  * if flags has AE_TIME_EVENTS set, time events are processed. 
  22.  * 如果 flags 包含 AE_TIME_EVENTS ,那么处理时间事件。 
  23.  * 
  24.  * if flags has AE_DONT_WAIT set the function returns ASAP until all 
  25.  * the events that's possible to process without to wait are processed. 
  26.  * 如果 flags 包含 AE_DONT_WAIT , 
  27.  * 那么函数在处理完所有不许阻塞的事件之后,即刻返回。 
  28.  * 
  29.  * The function returns the number of events processed.  
  30.  * 函数的返回值为已处理事件的数量 
  31.  */  
  32. int aeProcessEvents(aeEventLoop *eventLoop, int flags)  
  33. {  
  34.     int processed = 0, numevents;  
  35.   
  36.     /* Nothing to do? return ASAP */  
  37.     if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0;  
  38.   
  39.     /* Note that we want call select() even if there are no 
  40.      * file events to process as long as we want to process time 
  41.      * events, in order to sleep until the next time event is ready 
  42.      * to fire. */  
  43.     if (eventLoop->maxfd != -1 ||  
  44.         ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) {  
  45.         int j;  
  46.         aeTimeEvent *shortest = NULL;  
  47.         struct timeval tv, *tvp;  
  48.   
  49.         // 获取最近的时间事件  
  50.         if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT))  
  51.             shortest = aeSearchNearestTimer(eventLoop);  
  52.         if (shortest) {  
  53.             // 如果时间事件存在的话  
  54.             // 那么根据最近可执行时间事件和现在时间的时间差来决定文件事件的阻塞时间  
  55.             long now_sec, now_ms;  
  56.   
  57.             /* Calculate the time missing for the nearest 
  58.              * timer to fire. */  
  59.             // 计算距今最近的时间事件还要多久才能达到  
  60.             // 并将该时间距保存在 tv 结构中  
  61.             aeGetTime(&now_sec, &now_ms);  
  62.             tvp = &tv;  
  63.             tvp->tv_sec = shortest->when_sec - now_sec;  
  64.             if (shortest->when_ms < now_ms) {  
  65.                 tvp->tv_usec = ((shortest->when_ms+1000) - now_ms)*1000;  
  66.                 tvp->tv_sec --;  
  67.             } else {  
  68.                 tvp->tv_usec = (shortest->when_ms - now_ms)*1000;  
  69.             }  
  70.   
  71.             // 时间差小于 0 ,说明事件已经可以执行了,将秒和毫秒设为 0 (不阻塞)  
  72.             if (tvp->tv_sec < 0) tvp->tv_sec = 0;  
  73.             if (tvp->tv_usec < 0) tvp->tv_usec = 0;  
  74.         } else {  
  75.               
  76.             // 执行到这一步,说明没有时间事件  
  77.             // 那么根据 AE_DONT_WAIT 是否设置来决定是否阻塞,以及阻塞的时间长度  
  78.   
  79.             /* If we have to check for events but need to return 
  80.              * ASAP because of AE_DONT_WAIT we need to se the timeout 
  81.              * to zero */  
  82.             if (flags & AE_DONT_WAIT) {  
  83.                 // 设置文件事件不阻塞  
  84.                 tv.tv_sec = tv.tv_usec = 0;  
  85.                 tvp = &tv;  
  86.             } else {  
  87.                 /* Otherwise we can block */  
  88.                 // 文件事件可以阻塞直到有事件到达为止  
  89.                 tvp = NULL; /* wait forever */  
  90.             }  
  91.         }  
  92.   
  93.         // 处理文件事件,阻塞时间由 tvp 决定  
  94.         numevents = aeApiPoll(eventLoop, tvp);  
  95.         for (j = 0; j < numevents; j++) {  
  96.             // 从已就绪数组中获取事件  
  97.             aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd];  
  98.   
  99.             int mask = eventLoop->fired[j].mask;  
  100.             int fd = eventLoop->fired[j].fd;  
  101.             int rfired = 0;  
  102.   
  103.             /* note the fe->mask & mask & ... code: maybe an already processed 
  104.              * event removed an element that fired and we still didn't 
  105.              * processed, so we check if the event is still valid. */  
  106.             if (fe->mask & mask & AE_READABLE) {  
  107.                 // 读事件  
  108.                 rfired = 1; // 确保读/写事件只能执行其中一个  
  109.                 fe->rfileProc(eventLoop,fd,fe->clientData,mask);  
  110.             }  
  111.             if (fe->mask & mask & AE_WRITABLE) {  
  112.                 // 写事件  
  113.                 if (!rfired || fe->wfileProc != fe->rfileProc)  
  114.                     fe->wfileProc(eventLoop,fd,fe->clientData,mask);  
  115.             }  
  116.   
  117.             processed++;  
  118.         }  
  119.     }  
  120.   
  121.     /* Check time events */  
  122.     // 执行时间事件  
  123.     if (flags & AE_TIME_EVENTS)  
  124.         processed += processTimeEvents(eventLoop);  
  125.   
  126.     return processed; /* return the number of processed file/time events */  
  127. }  

说明:通过使用不同的flag标记来使其执行不同的操作。需要注意的是在处理文件事件时的处理方式:

如果有处于监控中的文件fd则直接根据传入的flag是否等待来决定是否阻塞。如果不需要等待则aepoll不阻塞,如果需要等待则aepoll阻塞直到有事件发生。

如果没有处于监控中的fd则判断是否需要处理时间事件如果需要则根据最近可执行时间事件和现在时间的时间差来决定文件事件的阻塞时间。

prcessTimeEvents

[cpp] view plaincopy
  1. /* Process time events 
  2.  * 
  3.  * 处理所有已到达的时间事件 
  4.  */  
  5. static int processTimeEvents(aeEventLoop *eventLoop) {  
  6.     int processed = 0;  
  7.     aeTimeEvent *te;  
  8.     long long maxId;  
  9.     time_t now = time(NULL);  
  10.   
  11.     /* If the system clock is moved to the future, and then set back to the 
  12.      * right value, time events may be delayed in a random way. Often this 
  13.      * means that scheduled operations will not be performed soon enough. 
  14.      * 
  15.      * Here we try to detect system clock skews, and force all the time 
  16.      * events to be processed ASAP when this happens: the idea is that 
  17.      * processing events earlier is less dangerous than delaying them 
  18.      * indefinitely, and practice suggests it is. */  
  19.     // 通过重置事件的运行时间,  
  20.     // 防止因时间穿插(skew)而造成的事件处理混乱  
  21.     if (now < eventLoop->lastTime) {  
  22.         te = eventLoop->timeEventHead;  
  23.         while(te) {  
  24.             te->when_sec = 0;  
  25.             te = te->next;  
  26.         }  
  27.     }  
  28.     // 更新最后一次处理时间事件的时间  
  29.     eventLoop->lastTime = now;  
  30.   
  31.     te = eventLoop->timeEventHead;  
  32.     maxId = eventLoop->timeEventNextId-1;  
  33.     while(te) {  
  34.         long now_sec, now_ms;  
  35.         long long id;  
  36.   
  37.         // 跳过无效事件  
  38.         if (te->id > maxId) {  
  39.             te = te->next;  
  40.             continue;  
  41.         }  
  42.           
  43.         // 获取当前时间  
  44.         aeGetTime(&now_sec, &now_ms);  
  45.   
  46.         // 如果当前时间等于或等于事件的执行时间,那么执行这个事件  
  47.         if (now_sec > te->when_sec ||  
  48.             (now_sec == te->when_sec && now_ms >= te->when_ms))  
  49.         {  
  50.             int retval;  
  51.   
  52.             id = te->id;  
  53.             retval = te->timeProc(eventLoop, id, te->clientData);  
  54.             processed++;  
  55.             /* After an event is processed our time event list may 
  56.              * no longer be the same, so we restart from head. 
  57.              * Still we make sure to don't process events registered 
  58.              * by event handlers itself in order to don't loop forever. 
  59.              * To do so we saved the max ID we want to handle. 
  60.              * 
  61.              * FUTURE OPTIMIZATIONS: 
  62.              * Note that this is NOT great algorithmically. Redis uses 
  63.              * a single time event so it's not a problem but the right 
  64.              * way to do this is to add the new elements on head, and 
  65.              * to flag deleted elements in a special way for later 
  66.              * deletion (putting references to the nodes to delete into 
  67.              * another linked list). */  
  68.   
  69.             // 记录是否有需要循环执行这个事件时间  
  70.             if (retval != AE_NOMORE) {  
  71.                 // 是的, retval 毫秒之后继续执行这个时间事件  
  72.                 aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms);  
  73.             } else {  
  74.                 // 不,将这个事件删除  
  75.                 aeDeleteTimeEvent(eventLoop, id);  
  76.             }  
  77.   
  78.             // 因为执行事件之后,事件列表可能已经被改变了  
  79.             // 因此需要将 te 放回表头,继续开始执行事件  
  80.             te = eventLoop->timeEventHead;  
  81.         } else {  
  82.             te = te->next;  
  83.         }  
  84.     }  
  85.     return processed;  
  86. }  

说明:

在处理完一个事件以后我们的事件列表可能产生了变化,因而我们需要从头开始再遍历处理。

同时为了确保我们下一次处理的事件不是由当前处理的事件所注册的,我们通过保存当前处理的handle作为最大的handle来避免。

总结

对于Ae事件处理的理解主要依赖于对基于事件的异步编程框架的理解,底层的关于网络poll的会在后面的文章中进一步的说明。

0 0
原创粉丝点击