ngx_http_core_init_main_conf

发布于:2025-03-29 ⋅ 阅读:(42) ⋅ 点赞:(0)

定义在 src\http\ngx_http_core_module.c 

static char *
ngx_http_core_init_main_conf(ngx_conf_t *cf, void *conf)
{
    ngx_http_core_main_conf_t *cmcf = conf;

    ngx_conf_init_uint_value(cmcf->server_names_hash_max_size, 512);
    ngx_conf_init_uint_value(cmcf->server_names_hash_bucket_size,
                             ngx_cacheline_size);

    cmcf->server_names_hash_bucket_size =
            ngx_align(cmcf->server_names_hash_bucket_size, ngx_cacheline_size);


    ngx_conf_init_uint_value(cmcf->variables_hash_max_size, 1024);
    ngx_conf_init_uint_value(cmcf->variables_hash_bucket_size, 64);

    cmcf->variables_hash_bucket_size =
               ngx_align(cmcf->variables_hash_bucket_size, ngx_cacheline_size);

    if (cmcf->ncaptures) {
        cmcf->ncaptures = (cmcf->ncaptures + 1) * 3;
    }

    return NGX_CONF_OK;
}

ngx_http_core_init_main_conf 函数是 Nginx HTTP 核心模块用于初始化主配置结构体(ngx_http_core_main_conf_t)的回调函数


ngx_http_core_main_conf_t *cmcf = conf;

作用 :将传入的通用配置指针 conf 强制转换为 ngx_http_core_main_conf_t 类型指针。

逻辑 conf 是 Nginx 配置框架传递的通用配置结构体指针,需显式转换为 HTTP 核心模块的主配置结构体类型,以便访问其成员。

意义 :为后续操作提供类型安全的结构体访问能力。

 


ngx_conf_init_uint_value(cmcf->server_names_hash_max_size, 512);

作用 :初始化 server_names_hash_max_size 的默认值。

逻辑 :如果用户未在配置文件中显式设置该值,则将其设为 512

意义 :server_names_hash_max_size 定义服务器名称哈希表(用于虚拟主机匹配)的最大容量。默认值 512 是 Nginx 的经验值,平衡内存占用和性能。


ngx_conf_init_uint_value(cmcf->server_names_hash_bucket_size, ngx_cacheline_size);

作用 :初始化 server_names_hash_bucket_size 的默认值。

逻辑 :若用户未配置,则使用 ngx_cacheline_size(通常为 CPU 缓存行大小,如 64 字节)。

意义 :哈希表的桶大小需对齐到 CPU 缓存行,减少伪共享(False Sharing),提升并发访问性能。

此时 ngx_cacheline_size=64

cmcf->server_names_hash_bucket_size=64


    cmcf->server_names_hash_bucket_size =
            ngx_align(cmcf->server_names_hash_bucket_size, ngx_cacheline_size);

作用 :强制对齐 server_names_hash_bucket_size

逻辑 :使用 ngx_align 将其值对齐到 ngx_cacheline_size 的倍数。

意义 :确保哈希表的桶大小是缓存行的整数倍,优化内存访问效率。

此时 cmcf->server_names_hash_bucket_size=64


 

ngx_conf_init_uint_value(cmcf->variables_hash_max_size, 1024);

作用 :初始化变量哈希表的最大容量。

逻辑 :若用户未配置,默认设为 1024

意义 variables_hash_max_size 控制 Nginx 变量存储的哈希表大小,影响变量查找性能。


ngx_conf_init_uint_value(cmcf->variables_hash_bucket_size, 64);

作用 :初始化变量哈希表的桶大小。

逻辑 :默认值为 64(通常与缓存行对齐)。

意义 :较小的桶大小适合变量哈希表的负载特性,平衡内存和性能。

 


    cmcf->variables_hash_bucket_size =
               ngx_align(cmcf->variables_hash_bucket_size, ngx_cacheline_size);

作用 :对齐变量哈希表的桶大小。

逻辑 :强制对齐到 ngx_cacheline_size

意义 :与第 4 行类似,优化变量哈希表的内存访问效率。


if (cmcf->ncaptures) { cmcf->ncaptures = (cmcf->ncaptures + 1) * 3; }

作用 :调整正则表达式捕获组数量。

逻辑 :若用户配置了 ncaptures(正则表达式捕获组数量),则将其值更新为 (ncaptures + 1) * 3

意义 :扩容策略可能是为了预分配内存,避免动态扩容开销。例如,若用户配置 ncaptures=2,实际分配 (2+1)*3=9 个捕获组,满足复杂正则表达式的潜在需求。

此时 cmcf->ncaptures=0,条件不成立

 


return NGX_CONF_OK;

作用 :返回配置初始化结果。

逻辑 :固定返回 NGX_CONF_OK,表示初始化成功。

意义 :告知 Nginx 配置框架当前模块的初始化已完成且无错误。


 


网站公告

今日签到

点亮在社区的每一天
去签到