>  기사  >  백엔드 개발  >  안녕하세요 모듈 작성

안녕하세요 모듈 작성

WBOY
WBOY원래의
2016-08-08 09:24:061148검색

고성능 동시서버를 배우기 위해 Nginx 구현을 공부할 예정입니다. 관례에 따르면 처음에 hello world 프로그램을 작성해야 하므로 다음 단계에서는 Nginx 프레임워크에서 "Hello World"를 인쇄하는 간단한 HTTP 모듈을 작성하는 방법을 소개합니다.

hello 구성 항목 처리 정의

먼저 모듈의 구성 파일 매개변수를 정의하기 위해 명령 배열을 정의해야 합니다. 각 배열 요소는 ngx_command_t 유형이며 배열의 끝은 ngx_null_command로 끝납니다.

Nginx는 구성 파일의 구성 항목을 구문 분석할 때 먼저 모든 모듈을 순회합니다. 각 모듈에 대해 명령 배열을 순회합니다. 각 ngx_command_t 구조는 관심 있는 구성 항목을 정의합니다. 구조는 다음과 같이 정의됩니다.

<code><span>struct</span> ngx_command_s {
    <span>/* 配置项名称 */</span>
    ngx_str_t             name;
    <span>/* 指定配置项可以出现的位置 */</span>
    ngx_uint_t            type;
    <span>/* 出现了name中指定的配置项后,将会调用set方法处理配置项的参数 */</span><span>char</span>               *(*<span>set</span>)(ngx_conf_t *cf, ngx_command_t *cmd, <span>void</span> *conf);
    ngx_uint_t            conf;
    <span>/* 在配置文件中的偏移量 */</span>
    ngx_uint_t            offset;
    <span>/* 配置项读取后的处理过程,必须是ngx_conf_post_t结构的指针 */</span><span>void</span>                 *post;
};

<span>#define ngx_null_command  { ngx_null_string, 0, NULL, 0, 0, NULL }</span></code>

명령어 배열을 이해한 후 hello 구성 항목의 처리를 정의합니다.

<code><span>static</span> ngx_command_t ngx_http_hello_commands[] = {

    {   ngx_string(<span>"hello"</span>),
        NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS,
        ngx_http_hello,
        NGX_HTTP_LOC_CONF_OFFSET,
        <span>0</span>,
        NULL },

    ngx_null_command
};</code>

그중 ngx_http_hello는 의 집합 멤버입니다. ngx_command_t 구조 특정 구성 블록에 hello 구성 항목이 나타나면 Nginx는 ngx_http_hello 메서드를 호출합니다. 다음은 ngx_http_hello의 구현입니다.

<code><span>static</span><span>char</span> *
ngx_http_hello(ngx_conf_t *cf, ngx_command_t *cmd, <span>void</span> *conf)
{
    ngx_http_core_loc_conf_t *clcf;

    <span>/* 首先找到hello配置项所属的配置块 */</span>
    clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);

    <span>/* HTTP框架在处理用户请求进行到NGX_HTTP_CONTENT_PHASE阶段时
     * 如果请求的主机域名、URI与hello配置项所在的配置块相匹配
     * 则调用ngx_http_hello_handler方法处理这个请求
     */</span>
    clcf->handler = ngx_http_hello_handler;

    <span>return</span> NGX_CONF_OK;
}</code>

hello 모듈 정의

HTTP 모듈을 정의하는 방법은 매우 간단합니다. 다음과 같이 ngx_moodule_t 구조를 정의하면 됩니다.

<code>ngx_module_t ngx_http_hello_module = {
    NGX_MODULE_V1,
    &ngx_http_hello_module_ctx,    <span>/* module context */</span>
    ngx_http_hello_commands,       <span>/* module directives */</span>
    NGX_HTTP_MODULE,               <span>/* module type */</span>
    NULL,                          <span>/* init master */</span>
    NULL,                          <span>/* init module */</span>
    NULL,                          <span>/* init process */</span>
    NULL,                          <span>/* init thread */</span>
    NULL,                          <span>/* exit thread */</span>
    NULL,                          <span>/* exit process */</span>
    NULL,                          <span>/* exit master */</span>
    NGX_MODULE_V1_PADDING
};</code>

컴파일 중에 hello 모듈이 ngx_modules 전역 배열에 추가됩니다.

여기서 ngx_http_hello_commands는 이전 섹션에서 정의한 hello 구성 항목을 처리하는 것입니다.

HTTP 모듈을 정의하는 것이므로 typeNGX_HTTP_MODULE로 설정해야 합니다.

중요한 멤버 void* ctx도 있습니다. HTTP 모듈의 경우 ctx 포인터가 ngx_http_module_t 인터페이스를 가리켜야 합니다.

HTTP 프레임워크는 구성 파일을 읽고 다시 로드할 때 ngx_http_module_t 인터페이스에서 설명하는 8단계를 정의합니다. HTTP 프레임워크가 시작되면 각 단계에서 ngx_http_module_t의 해당 메서드를 호출합니다. 작업이 필요하지 않은 경우 NULL로 정의할 수 있습니다. hello 모듈은 어떤 작업도 수행할 필요가 없으므로 다음과 같이 정의됩니다.

<code><span>static</span> ngx_http_module_t ngx_http_hello_module_ctx = {
    NULL,                          <span>/* preconfiguration */</span>
    NULL,                           <span>/* postconfiguration */</span>    NULL,                          <span>/* create main configuration */</span>
    NULL,                          <span>/* init main configuration */</span>    NULL,                          <span>/* create server configuration */</span>
    NULL,                          <span>/* merge server configuration */</span>    NULL,                           <span>/* create location configuration */</span>
    NULL                            <span>/* merge location configuration */</span>
};</code>

사용자 요청 처리

마지막 단계는 HTTP에 대한 약간의 지식입니다. 여기서는 HTTP 프로토콜 소개를 참조하세요. 우리는 다음과 같이 정의된 ngx_http_hello_handler 메소드를 구현하여 사용자 요청을 처리합니다.

<code><span>static</span> ngx_int_t
ngx_http_hello_handler(ngx_http_request_t *r)</code>

여기서 ngx_http_request_t 구조에는 요청된 모든 정보(예: 메소드, URI, 프로토콜 버전 번호 및 헤더)가 포함됩니다. 등), 또한 메모리 풀, 응답 헤더 등과 같은 다른 많은 멤버도 포함합니다.

GET 메소드와 HEAD 메소드만 다루기 때문에 다음과 같은 판단이 필요합니다.

<code><span>if</span> (!(r->method & (NGX_HTTP_GET | NGX_HTTP_HEAD))) {
        <span>return</span> NGX_HTTP_NOT_ALLOWED;
 }</code>

다음으로, 요청에 패키지 본문이 필요하지 않기 때문입니다. , 패키지 본문, 메서드를 다음과 같이 삭제해야 합니다.

<code>ngx_int_t rc = ngx_http_discard_request_body(r);
<span>if</span> (rc != NGX_OK) {
    <span>return</span> rc;
}</code>

그런 다음 반환된 응답 패킷을 설정합니다. 반환된 패킷 본문에는 "Hello World" 문자열만 포함됩니다.

<code>ngx_str_type = ngx_string(<span>"text/plain"</span>);
ngx_str_response = ngx_string(<span>"Hello World"</span>);
r->headers_out.status = NGX_HTTP_OK;
r->headers_out.content_length_n = response.len;
r->headers_out.content_type = type;</code>

마지막으로 전송된 응답 패킷의 헤더와 패키지 본문:

<code>    rc = ngx_http_send_header(r);
    <span>if</span> (rc == NGX_ERR || rc > NGX_OK || r->header_only) {
        <span>return</span> rc;
    }

    ngx_buf_t *b;
    b = ngx_create_temp_buf(r->pool, response.len);
    <span>if</span> (b == NULL) {
        <span>return</span> NGX_HTTP_INTERNAL_SERVER_ERROR;
    }

    ngx_memcpy(b->pos, response.data, response.len);
    b->last = b->pos + response.len;
    b->last_buf = <span>1</span>;

    ngx_chain_t out;
    out.buf = b;
    out.next = NULL;

    <span>/* send the buffer chain of your response */</span><span>return</span> ngx_http_output_filter(r, &out);</code>

전체 코드는 여기에서 볼 수 있습니다: hello_module

컴파일 및 실행

새 만들기 config 파일을 코드와 동일한 디렉터리에 추가하고 다음 몇 줄을 추가합니다:

<code>ngx_addon_name=ngx_http_hello_module
HTTP_MODULES=<span>"<span>$HTTP_MODULES</span> ngx_http_hello_module"</span>
NGX_ADDON_SRCS=<span>"<span>$NGX_ADDON_SRCS</span><span>$ngx_addon_dir</span>/ngx_http_hello_module.c"</span></code>

그런 다음 Nginx 소스 코드 루트 디렉터리를 입력하고 configure를 실행하고 –add-module 매개변수를 가져오는 것을 기억하세요. , 그리고 우리가 직접 작성한 HTTP 모듈 코드에 대한 경로가 있는 매개변수를 따르십시오.

<code>./configure --prefix=<span>/usr/local</span><span>/nginx --add-module=/code</span><span>/nginx-1.8.0/src</span><span>/http/hello</span>_module</code>

구성이 완료된 후 make 명령을 사용하여 컴파일한 후 make install를 입력하여 완료합니다. 설치.

/usr/local/nginx/conf/nginx.conf을 수정하고 다음을 추가합니다.

<code>http{
    <span>...</span>
    server {
        <span>...</span>
        location /hello {
            hello;
        }
        <span>...</span>
    }
    <span>...</span>
}</code>

Nginx를 실행한 다음 브라우저에 IP/hello를 입력하여 표시된 "Hello World 문자열"을 확인합니다.

참고자료

"Nginx에 대한 심층적인 이해"

위 내용은 다양한 측면을 포함하여 hello 모듈 작성 방법을 소개한 내용으로, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.