6">结束upstream请求
upstream请求的结束的流程,主要有三个函数:
ngx_http_upstream_finalize_request
ngx_http_upstream_cleanup
ngx_http_upstream_next
其中cleanup和next真正终止upstream时还是会调用到finalize_request函数。
ngx_http_upstream_cleanup函数在启动upstream时,会挂在到请求的cleanup链表中,当HTTP框架结束http请求时一定会调用到upstream_cleanup函数。
static void ngx_http_upstream_cleanup(void *data)
{
ngx_http_request_t *r = data;
ngx_http_upstream_finalize_request(r, r->upstream, NGX_DONE);
}
upstream_cleanup其实是直接调用了ngx_http_upstream_finalize_request,这是我们期望的关闭方式。
而ngx_http_upstream_next函数,是在处理请求的的流程中出现错误才会主动调用到,该函数通过重连服务器、选取新的服务器等策略来提高服务的可用性。
目前nginx的负载均衡的功能就是通过next函数来实现的,这里没有进行详细分析,只简单说明一下。
static void ngx_http_upstream_next(ngx_http_request_t *r, ngx_http_upstream_t *u, ngx_uint_t ft_type)
{
……
if (status) {
u->state->status = status;
timeout = u->conf->next_upstream_timeout;
// 当tries为0时,才最终结束upstream的请求
if (u->peer.tries == 0
|| !(u->conf->next_upstream & ft_type)
|| (timeout && ngx_current_msec – u->peer.start_time >= timeout))
{
ngx_http_upstream_finalize_request(r, u, status);
return;
}
}
// 由于要发起新的连接,所以需要先关闭和上游服务器的已有连接
if (u->peer.connection) {
if (u->peer.connection->pool) {
ngx_destroy_pool(u->peer.connection->pool);
}
ngx_close_connection(u->peer.connection);
u->peer.connection = NULL;
}
// 重新发起连接
ngx_http_upstream_connect(r, u);
}
最后看一下ngx_http_upstream_finalize_request的具体实现
static void ngx_http_upstream_finalize_request(ngx_http_request_t *r, ngx_http_upstream_t *u, ngx_int_t rc)
{
// 将cleanup指向的清理资源回调方法设置为NULL
if (u->cleanup) {
*u->cleanup = NULL;
u->cleanup = NULL;
}
// 释放解析主机域名时分配的资源
if (u->resolved && u->resolved->ctx) {
ngx_resolve_name_done(u->resolved->ctx);
u->resolved->ctx = NULL;
}
……
// 调用http模块实现的finalize_request方法
u->finalize_request(r, rc);
// 释放与上游的连接
if (u->peer.connection) {
if (u->peer.connection->pool) {
ngx_destroy_pool(u->peer.connection->pool);
}
ngx_close_connection(u->peer.connection);
}
u->peer.connection = NULL;
// 删除用于缓存响应的临时文件
if (u->store && u->pipe && u->pipe->temp_file
&& u->pipe->temp_file->file.fd != NGX_INVALID_FILE)
{
if (ngx_delete_file(u->pipe->temp_file->file.name.data)
== NGX_FILE_ERROR)
……
}
……
// 最后还是调用HTTP框架提供的方法结束请求
ngx_http_finalize_request(r, rc);
}
来源:freebuf.com 2020-12-10 18:05:09 by: stan1y