memcached允许用户设置数据的过期时间,那么memcached是如何管理过期数据的呢?
原理很简单:首先通过hash表查找该数据,然后判断该数据是否过期。如果过期,那么就将数据删除,否则将数据交给用户。
系统中有一个定时器事件。
-
/* libevent uses a monotonic clock when available for event scheduling. Aside
-
* from jitter, simply ticking our internal timer here is accurate enough.
-
* Note that users who are setting explicit dates for expiration times *must*
-
* ensure their clocks are correct before starting memcached. */
-
static void clock_handler(const int fd, const short which, void *arg) {
-
struct timeval t = {.tv_sec = 1, .tv_usec = 0};
-
static bool initialized = false;
-
-
evtimer_set(&clockevent, clock_handler, 0);
-
event_base_set(main_base, &clockevent);
-
evtimer_add(&clockevent, &t);
-
-
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
-
if (monotonic) {
-
struct timespec ts;
-
if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
-
return;
-
current_time = (rel_time_t) (ts.tv_sec - monotonic_start);
-
return;
-
}
-
#endif
-
{
-
struct timeval tv;
-
gettimeofday(&tv, NULL);
-
current_time = (rel_time_t) (tv.tv_sec - process_started);
-
}
-
}
可以看到事件驱动模型的魅力,大大简化了网络编程的难度。
事件驱动libevent库编程模型需如下几步:
1.为事件绑定处理函数
2.将事件绑定到event_base中(一般一个thread对应一个event_base,可以向event_base上绑定很多事件)
3.event_add(base,&timeout) 设置回调函数的最晚执行事件。
阅读(5650) | 评论(1) | 转发(1) |