Ubuntu 下 nginx-1.24.0 源码分析 - ngx_init_cycle 函数 - 详解(10)

详解(10)


初始化模块配置

c 复制代码
   if (ngx_cycle_modules(cycle) != NGX_OK) {
        ngx_destroy_pool(pool);
        return NULL;
    }


    for (i = 0; cycle->modules[i]; i++) {
        if (cycle->modules[i]->type != NGX_CORE_MODULE) {
            continue;
        }

        module = cycle->modules[i]->ctx;

        if (module->create_conf) {
            rv = module->create_conf(cycle);
            if (rv == NULL) {
                ngx_destroy_pool(pool);
                return NULL;
            }
            cycle->conf_ctx[cycle->modules[i]->index] = rv;
        }
    }

1 初始化模块列表

c 复制代码
if (ngx_cycle_modules(cycle) != NGX_OK) {
    ngx_destroy_pool(pool);
    return NULL;
}

调用 ngx_cycle_modules 初始化 cycle->modules 数组,该数组包含所有核心模块的指针。

Nginx 模块分为核心模块(NGX_CORE_MODULE)、事件模块、HTTP 模块等。ngx_cycle_modules 会遍历全局模块列表(ngx_modules),筛选出核心模块并按优先级排序。

若模块初始化失败(如内存不足),立即回滚资源。


ngx_cycle_modules


2 遍历核心模块

c 复制代码
for (i = 0; cycle->modules[i]; i++) {
    if (cycle->modules[i]->type != NGX_CORE_MODULE) {
        continue;
    }
    module = cycle->modules[i]->ctx;

遍历 cycle->modules,跳过非核心模块,获取核心模块的上下文(ctx)。

通过 type 区分模块类型,确保仅初始化核心模块的配置。


3 创建模块配置结构

c 复制代码
if (module->create_conf) {
    rv = module->create_conf(cycle);
    if (rv == NULL) {
        ngx_destroy_pool(pool);
        return NULL;
    }
    cycle->conf_ctx[cycle->modules[i]->index] = rv;
}

ngx_core_module_t *module;
modulengx_core_module_t 类型的指针

关于 ngx_core_module_t


调用模块的 create_conf 方法创建默认配置结构,并将其存储到 conf_ctx 数组的对应位置。

create_conf 返回模块特定的配置结构

conf_ctx 数组通过模块的 index 索引定位配置结构。

每个核心模块(如事件模块)需要独立的配置结构,conf_ctx 是全局配置的存储中心。


4 总结

代码行 核心意图 设计哲学
ngx_cycle_modules 模块筛选与排序 按类型和优先级管理模块,确保初始化顺序正确。
module->type 检查 模块分类处理 仅处理核心模块,避免干扰其他模块(如 HTTP 模块)。
create_conf 调用 配置结构初始化 模块自定义配置,支持灵活扩展。
conf_ctx 存储 配置集中管理 通过索引快速访问模块配置,提升效率。

相关推荐
格调UI成品4 分钟前
DCS+PLC协同优化:基于MQTT的分布式控制系统能效提升案例
数据库·云边协同
空灵之海19 分钟前
Ubuntu系统安全合规配置
linux·ubuntu·系统安全·1024程序员节
牵牛老人1 小时前
Qt C++ 复杂界面处理:巧用覆盖层突破复杂界面处理难题之一
数据库·c++·qt
GBASE1 小时前
GBASE南大通用技术分享:构建最优数据平台,GBase 8s数据库安装准备(三)
数据库
言之。1 小时前
Django REST Framework 中 @action 装饰器详解
数据库·sqlite
Linux运维技术栈3 小时前
域名网页加载慢怎么解决:从测速到优化的全链路性能优化实战
运维·网络·nginx·性能优化·cloudflare
十八旬3 小时前
苍穹外卖项目实战(day7-1)-缓存菜品和缓存套餐功能-记录实战教程、问题的解决方法以及完整代码
java·数据库·spring boot·redis·缓存·spring cache
笨鸟贤妃4 小时前
Ubuntu 22.04 安装 Docker & Compose 最新最简单完整指南
ubuntu·docker·compose
leo__5204 小时前
在Ubuntu 22.04系统中无需重启设置静态IP地址
tcp/ip·ubuntu·php
荣光波比4 小时前
Nginx 实战系列(六)—— Nginx 性能优化与防盗链配置指南
运维·nginx·性能优化·云计算