9.3.2 主动连接
作为Web服务器,Nginx也需要向其他服务器主动发起连接,当然,这样的连接与上一节介绍的被动连接是不同的,它使用ngx_peer_connection_t结构体来表示主动连接。不过,一个待处理连接的许多特性在被动连接结构体ngx_connection_t中都定义过了,因此,在ngx_peer_connection_t结构体中引用了ngx_connection_t这个结构体,下面我们来看一下其定义。
typedef struct ngx_peer_connection_s ngx_peer_connection_t;
//当使用长连接与上游服务器通信时,可通过该方法由连接池中获取一个新连接
typedef ngx_int_t(ngx_event_get_peer_pt)(ngx_peer_connection_tpc,void*data);
//当使用长连接与上游服务器通信时,通过该方法将使用完毕的连接释放给连接池
typedef void(ngx_event_free_peer_pt)(ngx_peer_connection_tpc,void*data,ngx_uint_t state);
struct ngx_peer_connection_s{
/一个主动连接实际上也需要ngx_connection_t结构体中的大部分成员,并且出于重用的考虑而定义了connection成员/
ngx_connection_t*connection;
//远端服务器的socket地址
struct sockaddr*sockaddr;
//sockaddr地址的长度
socklen_t socklen;
//远端服务器的名称
ngx_str_t*name;
/表示在连接一个远端服务器时,当前连接出现异常失败后可以重试的次数,也就是允许的最多失败次数/
ngx_uint_t tries;
//获取连接的方法,如果使用长连接构成的连接池,那么必须要实现get方法
ngx_event_get_peer_pt get;
//与get方法对应的释放连接的方法
ngx_event_free_peer_pt free;
/这个data指针仅用于和上面的get、free方法配合传递参数,它的具体含义与实现get方法、free方法的模块相关,可参照ngx_event_get_peer_pt和ngx_event_free_peer_pt方法原型中的data参数/
void*data;
//本机地址信息
ngx_addr_t*local;
//套接字的接收缓冲区大小
int rcvbuf;
//记录日志的ngx_log_t对象
ngx_log_t*log;
//标志位,为1时表示上面的connection连接已经缓存
unsigned cached:1;
/与9.3.1节中ngx_connection_t里的log_error意义是相同的,区别在于这里的log_error只有两位,只能表达4种错误,NGX_ERROR_IGNORE_EINVAL错误无法表达/
unsigned log_error:2;
};
ngx_peer_connection_t也有一个ngx_connection_t类型的成员,怎么理解这两个结构体之间的关系呢?所有的事件消费模块在每次使用ngx_peer_connection_t对象时,一般都需要重新生成一个ngx_peer_connection_t结构体,然而,ngx_peer_connection_t对应的ngx_connection_t连接一般还是从连接池中获取,因此,ngx_peer_connection_t只是对ngx_connection_t结构体做了简单的包装而已。