Ngx_connection_s 结构体分析报告

来源:互联网 发布:js按钮点击事件 定时 编辑:程序博客网 时间:2024/05/22 11:58

一、Ngx_connection_s结构体

struct ngx_connection_s {

    void               *data;//数据指针

    ngx_event_t        *read;//事件读操作

    ngx_event_t        *write;//事件写操作

    ngx_socket_t        fd;//用于socket通信的句柄

    ngx_recv_pt         recv;//接受指针,操作系统专有的接受指针

    ngx_send_pt         send;//发送指针,

    ngx_recv_chain_pt   recv_chain;//接受链表

    ngx_send_chain_pt   send_chain;//发送链表

    ngx_listening_t    *listening;//监听结构体

    off_t               sent;

    ngx_log_t          *log;//日志指针

    ngx_pool_t         *pool;//内存池指针

    struct sockaddr    *sockaddr;//socket地址指针

    socklen_t           socklen;//sock长度???

    ngx_str_t           addr_text;//地址文本信息

#if (NGX_SSL)

    ngx_ssl_connection_t  *ssl;//如果建立了连接,根据编译器的功能,选择是否建立ssl连接

#endif

    struct sockaddr    *local_sockaddr;//当地socket地址

    ngx_buf_t          *buffer;//缓存指针

    ngx_queue_t         queue;//队列指针

    ngx_atomic_uint_t   number;//原子操作序号

    ngx_uint_t          requests;//请求号

    unsigned            buffered:8;//buffer序号

    unsigned            log_error:3;     /* ngx_connection_log_error_e 日志出错编号*/

    unsigned            single_connection:1;//单连

    unsigned            unexpected_eof:1;//???

    unsigned            timedout:1;//是否超时

    unsigned            error:1;//如果错误,错误编码

    unsigned            destroyed:1;//破坏编码???

    unsigned            idle:1;//是否空闲

    unsigned            reusable:1;//是否可用

    unsigned            close:1;//是否关闭

    unsigned            sendfile:1;//是否发送文件

    unsigned            sndlowat:1;//操作是否可用,包括读写操作

    unsigned            tcp_nodelay:2;   /* ngx_connection_tcp_nodelay_e */

    unsigned            tcp_nopush:2;    /* ngx_connection_tcp_nopush_e */

#if (NGX_HAVE_IOCP)

unsigned            accept_context_updated:1;

//在配置过程中,是否打开系统I/O Completion Port功能

#endif

#if (NGX_HAVE_AIO_SENDFILE)

    unsigned            aio_sendfile:1;//异步IO发送文件

ngx_buf_t          *busy_sendfile;

//打开系统关于处理IO分发文件的操作

#endif

#if (NGX_THREADS)

    ngx_atomic_t        lock;//线程锁,原子操作

#endif

};

二、Ngx_connection_s结构体的架构使用分析

层级结构

结构原因

好处

缺点

Nginx状态机模型

Nginx采用进程/线程池+状态机的模型, 

1进程/线程不会因为连接的增多而增多;

2避免内存和系统调度切换的成本

对程序逻辑性要求较高,需要将一个连接拆分出若干个逻辑状态

Ngx_connect_t

Nginx内核对连接的抽象数据结构

层次化设计,利于编程实现,优化接口

event模块

ngx_event_process_init 函数中预先分配好。ngx_event_process_init预分配connectsread\write 事件的数组

http模块

建立连接,主要是按照

创建监听

开启监听

绑定监听

Connect连接

关闭连接

释放连接

挂载到可重用的连接上

Aio模块

负责外部异步io操作

交给外部部件来处理耗时较多的IO操作

Mail模块

Mail服务

epoll_module模块

特别重要,高并发的核心模块