欢迎您的访问
专注于分享最有价值的互联网技术干货

二十一、Nginx的基础架构解析(下)

几个T的资料等你来白嫖
双倍快乐
资源帮找!!!

Nginx的基础架构解析(下)

1. Nginx模块

1.1 Nginx中的模块化设计

Nginx 的内部结构是由核心部分和一系列的功能模块所组成。这样划分是为了使得每个模块的功能相对简单,便于开发,同时也便于对系统进行功能扩展。Nginx 将各功能模块组织成一条链,当有请求到达的时候,请求依次经过这条链上的部分或者全部模块,进行处理。例如前面讲到的 http 请求,会有11个处理阶段,而每个阶段有对应着许多在此阶段生效的模块对该 http 请求进行处理。同时,Nginx 开放了第三方模块编写功能,用户可以自定义模块,控制 http 请求的处理与响应,这种高度可定制化催生了 Nginx 的大量第三方模块,也使得 Nginx 定制化开发在各大互联网公司十分流行。

1.2 Nginx中的模块分类

关于 Nginx 模块的分类有很多种方式,目前网上博客中写的较多的是按照功能进行分类,有如下几大类:

  • event 模块: 搭建 独立于操作系统的事件处理机制的框架,以及 提供各种具体事件的处理。代表性的模块有:ngx_events_module, ngx_event_core_module, ngx_epoll_module;
  • handler 模块: 主要负责处理客户端请求并产生待响应的内容,比如 ngx_http_static_module 模块,负责客户端的静态页面请求处理并将对应的磁盘 文件准备为响应内容输出;
  • filter 模块: 主要 负责处理输出的内容,包括修改输出内容。代表性的模块有: ngx_http_sub_module;
  • upstream 模块: 该类模块都是用于实现反向代理功能,将真正的请求转发到后端服务器上,并从后端服务器上读取响应,发回给客户端。比如前面介绍到转发 http、websocket、grpc、rtmp等协议的模块都可以划分为这一类;
  • 负载均衡模块: 负载均衡的模块,实现相应算法。这类模块都是用于实现 Nginx 的负载均衡功能。
  • extend 模块: 又称第三方模块,非 Nginx 官方提供,由各大企业的开发人员结合自身业务开发而成。Nginx 提供了非常好的模块编写机制,遵循相关的标准可以很快定制出符合我们业务场景的模块,而且内部调用 Nginx 内部提供的方法进行处理,使得第三方模块往往都具备很好的性能

对于官方提供的模块,我们可以直接在官网文档上学习,学习的方式和学习其他互联网组件的方式一致,首先学习如何使用,在用至熟练后可以深入分析其源码了解功能实现背后的原理。

我们以前面介绍到的 Nginx 的限速模块(limit_req模块)进行说明。首先是掌握该模块的用法,在该模块的官方地址中,有关于该模块的详细介绍,包括该模块提供的所有指令以及所有变量说明。此外,还有比较丰富的指令用例。在多次使用该指令并自认为掌握了该模块的用法之后,想了解限速背后的原理以及相关算法时,就可以深入到源码学习了。

进入 Nginx 的源码目录,使用ls查看源码文件,限速模块是在 http 目录中的。

[root@server nginx-1.17.6]# cd src/

[root@server src]# ls
core  event  http  mail  misc  os  stream

[root@server src]# ls http/modules/ngx_http_limit_*.c
http/modules/ngx_http_limit_conn_module.c
http/modules/ngx_http_limit_req_module.c

找到 Nginx 模块对应的代码文件后,我们就可以阅读里面的代码进行学习。往往源码的阅读是枯燥无味的,我们可以借助海量的网络资源辅助我们学习。这里就有一篇文章,作者深入分析了 Nginx 的限流模块的源码以及相应限流算法,最后进行了相关的实验测试。通过这样一个个模块深入学习,最后在使用每一个 Nginx 指令时,也会非常熟练,最后成为 Nginx 高手。

1.3 如何学习和使用第三方模块

这里我们演示在 Nginx 中使用第三方模块。 Openresty 社区提供了一款 Nginx 中的 Echo 模块,即echo-nginx-module。在 Nginx 中添加了该模块后,我们在配置文件中可以使用该模块提供的 echo 指令返回用户响应,简单方便。该模块的源码在 github 上,并且有良好的文档和使用示例,非常方便开发者使用。

20210320154900936.jpg

现在我们在 Nginx 的源码编译阶段加入该第三方模块,具体操作如下:

[root@server shencong]# pwd
/root/shencong
[root@server shencong]# mkdir nginx-echo
# 下载 nginx 源码包和第三方模块的源码包 
[root@server shencong]# wget http://nginx.org/download/nginx-1.17.6.tar.gz
[root@server shencong]# wget https://github.com/openresty/echo-nginx-module/archive/v0.62rc1.tar.gz

# 解压
[root@server shencong]# tar -xzf nginx-1.17.6.tar.gz
[root@server shencong]# tar -xzf v0.62rc1.tar.gz

[root@server shencong]# ls
echo-nginx-module-0.62rc1  nginx-1.17.6  nginx-1.17.6.tar.gz  nginx-echo  v0.62rc1.tar.gz

[root@server shencong]# cd nginx-1.17.6
# 使用--add-module添加第三方模块,参数为第三方模块源码
[root@server shencong]# ./configure --prefix=/root/shencong/nginx-echo  --add-module=/root/shencong/echo-nginx-module-0.62rc1

编译完成后,我们就可以去nginx-echo目录中的 nginx.conf文件中添加echo 指令 。准备如下的配置(可以参参考社区提供的示例):

...
http {
   server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        # 新增测试 echo 指令配置
        location /timed_hello {
            default_type text/plain;
            echo_reset_timer;
            echo hello world;
            echo "'hello world' takes about $echo_timer_elapsed sec.";
            echo hiya igor;
            echo "'hiya igor' takes about $echo_timer_elapsed sec.";
        }

        location /echo_with_sleep {
            default_type text/plain;
            echo hello world;
            echo_flush;  # ensure the client can see previous output immediately
            echo_sleep   2.5;  # in sec
            echo "'hello' takes about $echo_timer_elapsed sec.";
        }

    }
}
...

启动 Nginx 后,我们就可以在浏览器上请求者两个 URI 地址,看到相应 echo 返回的信息了。第二个配置是使用了 echo_sleep 指令,会使得请求在休眠 2.5s 后才返回。
20210320154900986.jpg

20210320154901006.jpg

1.4 如何编写自己的模块

想要编写 Nginx 模块,首先需要对 Nginx 模块中的源码以及相关的数据结构有所了解,还要知晓 Nginx HTTP 模块的调用流程。假设我要实现前面第三方模块Echo的最简单形式,即只输出相应的字符串即可。假定模块支持的指令名称还是 echo, 这个 echo 指令需要跟一个参数,即输出的字符串。我们需要做如下几步:

  • 确定模块名称,以及模块中的指令以及参数,还有运行的环境。这里涉及的结构是 ngx_command_t,它定义了模块里的所有指令格式。下面的代码表示该模块中只有一个 echo 指令,它出现的上下文环境为 location,且有一个参数(NGX_CONF_TAKE1)。当某个配置块中出现echo指令时,Nginx 将调用ngx_http_echo方法。然后在该方法中,会设置处理请求的 handler,这个 handler 就是处理请求的方法。
static ngx_command_t  ngx_http_echo_commands[] = {  
         { ngx_string("echo"),      /* 指令名称,利用ngx_string宏定义 */
          NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,  /* 用在 location 指令块内,且有1个参数 */
          ngx_http_echo,            /* 处理回调函数 */
          NGX_HTTP_LOC_CONF_OFFSET,    
          offsetof(ngx_http_echo_loc_conf_t, ed), /* 指定参数读取位置 */
          NULL },
          ngx_null_command
  };
  • 完成请求处理的 handler 函数,最重要的部分就在这里;
static char *
 ngx_http_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
 {
     ngx_http_core_loc_conf_t  *clcf;
     /* 找到指令所属的配置块,这里我们限定echo指令的上下文环境只有location */
     clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
     /* 指定处理的handler */
     clcf->handler = ngx_http_echo_handler;
     ...
     return NGX_CONF_OK;
 }

 static ngx_int_t
 ngx_http_echo_handler(ngx_http_request_t *r)
 {
     ...

     /* 向用户发送相应包 */
     return ngx_http_output_filter(r, &out);
 }
  • 一些收尾工作,比如配置模块介入 http 请求的哪些阶段等。
/* Http context of the module */
  static ngx_http_module_t  ngx_http_echo_module_ctx = {
      NULL,                                  /* preconfiguration */
      NULL,                                  /* postconfiguration */
      NULL,                                  /* create main configuration */
      NULL,                                  /* init main configuration */
      NULL,                                  /* create server configuration */
      NULL,                                  /* merge server configuration */
      ngx_http_echo_create_loc_conf,         /* create location configration */
      ngx_http_echo_merge_loc_conf           /* merge location configration */
  };
  /* Module */
  ngx_module_t  ngx_http_echo_module = {
      NGX_MODULE_V1,
      &ngx_http_echo_module_ctx,             /* module context */
      ngx_http_echo_commands,                /* module directives */
      NGX_HTTP_MODULE,                       /* module type */
      NULL,                                  /* init master */
      NULL,                                  /* init module */
      NULL,                                  /* init process */
      NULL,                                  /* init thread */
      NULL,                                  /* exit thread */
      NULL,                                  /* exit process */
      NULL,                                  /* exit master */
      NGX_MODULE_V1_PADDING
  };

完成以上几步,一个简易的自定义模块就算大功告成了。接下来我们动手完成第一个自定义的模块,将其编译进Nginx 二进制文件中并进行测试。

2. 案例

我们来完成一个简单的自定义 http 模块,来实现前面Echo模块的最简单形式,即使用指令输出 “hello, world” 字符串。首先新建一个目录echo-nginx-module,然后在目录下新建两个文件configngx_http_echo_module.c

[root@server echo-nginx-module]# pwd
/root/shencong/echo-nginx-module

[root@server echo-nginx-module]# ls
config  ngx_http_echo_module.c

两个文件内容分别如下:

[root@server echo-nginx-module]# cat config 
ngx_addon_name=ngx_http_echo_module
# 指定模块名称
HTTP_MODULES="$HTTP_MODULES ngx_http_echo_module"
# 指定模块源码路径
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_echo_module.c"

[root@server echo-nginx-module]# cat ngx_http_echo_module.c
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>

/* Module config */
typedef struct {
    ngx_str_t  ed;
} ngx_http_echo_loc_conf_t;

static char *ngx_http_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static void *ngx_http_echo_create_loc_conf(ngx_conf_t *cf);
static char *ngx_http_echo_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child);

/* 定义指令 */
static ngx_command_t  ngx_http_echo_commands[] = {
    { ngx_string("echo"),      /* 指令名称,利用ngx_string宏定义 */
        NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,  /* 用在 location 指令块内,且有1个参数 */
        ngx_http_echo,         /* 处理回调函数 */
        NGX_HTTP_LOC_CONF_OFFSET,    
        offsetof(ngx_http_echo_loc_conf_t, ed), /* 指定参数读取位置 */
        NULL },
        ngx_null_command
};
/* Http context of the module */
static ngx_http_module_t  ngx_http_echo_module_ctx = {
    NULL,                                  /* preconfiguration */
    NULL,                                  /* postconfiguration */
    NULL,                                  /* create main configuration */
    NULL,                                  /* init main configuration */
    NULL,                                  /* create server configuration */
    NULL,                                  /* merge server configuration */
    ngx_http_echo_create_loc_conf,         /* create location configration */
    ngx_http_echo_merge_loc_conf           /* merge location configration */
};
/* Module */
ngx_module_t  ngx_http_echo_module = {
    NGX_MODULE_V1,
    &ngx_http_echo_module_ctx,             /* module context */
    ngx_http_echo_commands,                /* module directives */
    NGX_HTTP_MODULE,                       /* module type */
    NULL,                                  /* init master */
    NULL,                                  /* init module */
    NULL,                                  /* init process */
    NULL,                                  /* init thread */
    NULL,                                  /* exit thread */
    NULL,                                  /* exit process */
    NULL,                                  /* exit master */
    NGX_MODULE_V1_PADDING
};
/* Handler function */
static ngx_int_t
ngx_http_echo_handler(ngx_http_request_t *r)
{
    ngx_int_t rc;
    ngx_buf_t *b;
    ngx_chain_t out;
    ngx_http_echo_loc_conf_t *elcf;
    /* 获取指令的参数 */
    elcf = ngx_http_get_module_loc_conf(r, ngx_http_echo_module);
    if(!(r->method & (NGX_HTTP_HEAD|NGX_HTTP_GET|NGX_HTTP_POST)))
    {
        /* 如果不是 HEAD/GET/PUT 请求,则返回405 Not Allowed错误 */
        return NGX_HTTP_NOT_ALLOWED;
    }
    r->headers_out.content_type.len = sizeof("text/html") - 1;
    r->headers_out.content_type.data = (u_char *) "text/html";
    r->headers_out.status = NGX_HTTP_OK;
    r->headers_out.content_length_n = elcf->ed.len;
    if(r->method == NGX_HTTP_HEAD)
    {
        rc = ngx_http_send_header(r);
        if(rc != NGX_OK)
        {
            return rc;
        }
    }
    b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));
    if(b == NULL)
    {
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Failed to allocate response buffer.");
        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }
    out.buf = b;
    out.next = NULL;
    b->pos = elcf->ed.data;
    b->last = elcf->ed.data + (elcf->ed.len);
    b->memory = 1;
    b->last_buf = 1;
    rc = ngx_http_send_header(r);
    if(rc != NGX_OK)
    {
        return rc;
    }
    /* 向用户发送相应包 */
    return ngx_http_output_filter(r, &out);
}
static char *
ngx_http_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
    ngx_http_core_loc_conf_t  *clcf;
    clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
    /* 指定处理的handler */
    clcf->handler = ngx_http_echo_handler;
    ngx_conf_set_str_slot(cf,cmd,conf);
    return NGX_CONF_OK;
}
static void *
ngx_http_echo_create_loc_conf(ngx_conf_t *cf)
{
    ngx_http_echo_loc_conf_t  *conf;
    conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_echo_loc_conf_t));
    if (conf == NULL) {
        return NGX_CONF_ERROR;
    }
    conf->ed.len = 0;
    conf->ed.data = NULL;
    return conf;
}
static char *
ngx_http_echo_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
{
    ngx_http_echo_loc_conf_t *prev = parent;
    ngx_http_echo_loc_conf_t *conf = child;
    ngx_conf_merge_str_value(conf->ed, prev->ed, "");
    return NGX_CONF_OK;
}

这样一个第三方模块包就完成了,接下来我们要向之前使用第三方模块一样,将它编译进 Nginx,具体操作如下。

[root@server shencong]# cd nginx-1.17.6/
[root@server nginx-1.17.6]# ./configure --prefix=/root/shencong/nginx-echo --add-module=/root/shencong/echo-nginx-module
...
[root@server nginx-1.17.6] # make && make install
...
[root@server nginx-1.17.6]# cd ../nginx-echo/sbin/
[root@server sbin]# ./nginx -V
nginx version: nginx/1.17.6
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) 
configure arguments: --prefix=/root/shencong/nginx-echo --add-module=/root/shencong/echo-nginx-module

接下来,我们只要在 nginx.conf 中加入我们的指令,并给一个参数,就能看到我们自定义的输出了。

...
http {
   ...
   server {
       listen       80;
       server_name  localhost;
       location / {
            root   html;
            index  index.html index.htm;
       }

       location /test {
            echo hello,world;
       }
       ...
   }
}
...

最后我们请求主机的80端口,URI=/test,浏览器输出"hello, world",说明我们的自定义模块成功了!

20210320154901024.jpg

3. 小结

在 Nginx 基础架构介绍的最后,主要是介绍了 Nginx 的模块设计以及相应的模块用法。最后,我们简单给出了一个简单编写自己模块的案例作为本章的实战案例。希望这一节之后,大家能对 Nginx 的模块化设计有所了解,并有兴趣在模块的源码方向深入学习。

赞(0) 打赏
版权归原创作者所有,任何形式转载请联系我们:大白菜博客 » 二十一、Nginx的基础架构解析(下)

评论 抢沙发

7 + 3 =
  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏