nginx源码分析之配置图解

57 篇文章 0 订阅

nginx配置结构清晰,层次分明,这得益于整个架构的模块化设计,文本将揭示配置文件如何被处理和应用。

nginx源码分析之配置图解

 

整个配置文件解析后的结果如图这样存储。

一、解析的核心机制
nginx源码里,ngx_conf_t是解析的关键结构体
ngx_conf_handler函数里:

01 /* set up the directive's configuration context */
02 conf = NULL;
03 /* direct指令,一般是core类型模块指令,比如 daemon, work_processes */
04 if (cmd->type & NGX_DIRECT_CONF) {
05     conf = ((void **) cf->ctx)[ngx_modules[i]->index]; /* 直接存储,比如 ngx_core_conf_t */
06  
07 /* main指令,比如 events, http,此时指向它的地址,这样才能分配数组指针,存储属于它的结构体们。 */
08 else if (cmd->type & NGX_MAIN_CONF) {
09     conf = &(((void **) cf->ctx)[ngx_modules[i]->index]); /* 参考图片 */
10  
11 else if (cf->ctx) {
12     confp = *(void **) ((char *) cf->ctx + cmd->conf);
13  
14     /* 有移位的,因此http有三个部分,main, srv, conf,这个就为此而设计的,继续下面的sendfile指令 */
15      if (confp) {
16         conf = confp[ngx_modules[i]->ctx_index];
17     }
18 }
19  
20 rv = cmd->set(cf, cmd, conf);
21  
22 比如sendfile指令:
23 { ngx_string("sendfile"),
24   NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF
25                     |NGX_CONF_FLAG,
26   ngx_conf_set_flag_slot,
27   NGX_HTTP_LOC_CONF_OFFSET,  /* 这个对应上面理解,正因有这个offset,它才找到loc部分的配置 */
28   offsetof(ngx_http_core_loc_conf_t, sendfile),
29   NULL }

 二、配置的应用
1、最简单形式,direct方式

1 /* 定义获取配置文件的宏 */
2 #define ngx_get_conf(conf_ctx, module)  conf_ctx[module.index]
3  
4 ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);
5 if (ccf->master && ngx_process == NGX_PROCESS_SINGLE) {
6     ngx_process = NGX_PROCESS_MASTER;
7 }

2、稍微复杂点形式,main方式

1 /* 定义获取配置文件的宏,注意指针 */
2 #define ngx_event_get_conf(conf_ctx, module)                                  \
3              (*(ngx_get_conf(conf_ctx, ngx_events_module))) [module.ctx_index];
4  
5 ngx_epoll_conf_t  *epcf;
6  
7 epcf = ngx_event_get_conf(cycle->conf_ctx, ngx_epoll_module);
8  
9 nevents = epcf->events;

3、不简单的http配置

01 /* 宏定义,r是什么,稍后解释 */
02 #define ngx_http_get_module_loc_conf(r, module)  (r)->loc_conf[module.ctx_index]
03  
04 ngx_http_log_loc_conf_t  *lcf;
05  
06 lcf = ngx_http_get_module_loc_conf(r, ngx_http_log_module);
07 ...
08  
09  
10 /* r是请求,它是这么来的,在ngx_http_init_request函数里(ngx_http_request.c文件)*/
11  
12 r = ...;
13 cscf = addr_conf->default_server;
14  
15 r->main_conf = cscf->ctx->main_conf;
16 r->srv_conf = cscf->ctx->srv_conf;
17 r->loc_conf = cscf->ctx->loc_conf;

还有个要提的,http配置分main, src, loc,下级的配置可以覆盖上级,很明显,上级只是默认设置值而已。

三、重提模块化设计
学着用模块化的角度去看nginx的整体设计,一切以模块为核心,配置依赖于模块,即模块本身就携带着它的配置。正因为这样的设计的,配置文件的解析,使用非常简单。避免过多使用全局变量好像成为一种共识,但是在nginx世界里,全局变量可不少,每个模块都是个全局变量,为什么这样设计呢?因为模块之间是有依赖性的,所以需要互相访问。

配置文件解析这块的代码极具借鉴,本文只管窥般分析了配置文件,不能剥夺读者阅读源码的享受,点到即止。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值