再补充一下配置解析,Nginx 配置解析最大的亮点是用一个三级指针和 ctx 关联了起来,然后每个模块关注各自的配置专注解析和初始化就行了。
配置文件解析
ngx 在 main 函数执行的时候会调用 ngx_init_cycle,在这个过程中,会进行初始化的几个步骤:
-
create_conf 针对 core_module 类型的模块,将会调用 create_conf 方法:
-
-
并且把根据模块号存入了 cycle→conf_ctx 中。这个过程主要是进行配置数据结构的初始化。以epoll模块为例:
-
ngx_conf_parse 解析配置文件
这个函数一共有以下几个过程:
-
ngx_conf_read_token 这个过程主要进行配置配置的解析工作,解析完成的一个配置结构为:
struct ngx_conf_s {
char *name;
ngx_array_t *args;
ngx_cycle_t *cycle;
ngx_pool_t *pool;
ngx_pool_t *temp_pool;
ngx_conf_file_t *conf_file;
ngx_log_t *log;
void *ctx;
ngx_uint_t module_type;
ngx_uint_t cmd_type;
ngx_conf_handler_pt handler;
char *handler_conf;
};
-
ngx_conf_handler 进行配置的处理
-
cmd→set,以 ngx_http 模块为例
rv = ngx_conf_parse(cf, NULL) ; 在初始化完 http 的上下文之后,继续进行内部的解析逻辑。这样就会调用到 ngx_conf_handler 的下面部分逻辑:
-
init_conf阶段
core 模块将会按照配置项的值在这个阶段进行初始化。ngx 的配置架构如下:
整体架构
serv_conf 结构
loc_conf 结构