<aside> 💡 本文分析基于Redis-1.0源码,核心流程代码主要分布在redis.c,ae.c两个文件中。

</aside>

GitMind

Redis Server 与 Redis Client之间的核心AE事件流

Redis Server 与 Redis Client之间的核心AE事件流

Redis Server 与 Redis Client之间的核心AE事件流

Redis Server 与 Redis Client之间的核心AE事件流

Redis Server 与 Redis Client之间的核心AE事件流

Redis Server 与 Redis Client之间的核心AE事件流

1.Redis核心流程中的重要数据结构

struct redisServer {
    int port; 
    int fd; 
    redisDb *db;
    aeEventLoop *el;
		list *clients;
		...
};
typedef struct redisClient {
    int fd;
    redisDb *db;
    sds querybuf;
    list *reply;
} redisClient;
typedef struct redisDb {
    dict *dict;
    dict *expires;
    int id;
} redisDb;
typedef struct redisObject {
    void *ptr;
    int type;
    int refcount;
} robj;
typedef struct aeEventLoop {
    long long timeEventNextId;
    aeFileEvent *fileEventHead;
    aeTimeEvent *timeEventHead;
    int stop;
} aeEventLoop;

基于以上数据结构,Redis就可以构建核心的Server与client的交互流程

2.Redis核心流程解析

不像一些科学计算的程序,运行一次就可以产出所有结果。Redis功能是通过不断地对外界事件进行响应实现的。这种类型的程序,一般都存在事件循环线程,不断地响应,并处理外界事件。

int main(int argc, char **argv) {
    initServerConfig();
		...
    initServer();
    if (server.daemonize) daemonize();
    redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
		...
    if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
        acceptHandler, NULL, NULL) == AE_ERR) oom("creating file event");
    redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
    aeMain(server.el);
    aeDeleteEventLoop(server.el);
    return 0;
}
// ...表示略去的不重要的代码

在main函数入口中,主要做了三件事: