综述
Nginx作为反向代理服务器时,从后端服务器接收响应数据缓存在本地并发送给客户端。既然缓存在本地就要使用内存,如果一个请求的响应特别大,且可能nginx到客户端的发送速度比较慢就可能会导致请求全部缓存在内存中,导致内存使用偏高。nginx可以通过指令设置每个请求的响应body使用的缓冲区大小和数量。当出现缓冲区不足时就要将部分缓冲区的数据写入临时文件中,以释放部分缓冲区可再次缓存数据。
触发
在ngx_event_pipe_read_upstream()从上游接收数据时首先得准备缓冲区以存放数据。此时有可能出现空闲缓冲区不足的情况,因此需要将部分内存响应数据写入临时文件以释放这些缓冲区,如下:
// 迫不得已时才写临时文件
} else if (p->cacheable
|| p->temp_file->offset < p->max_temp_file_size)
{
/*
* if it is allowed, then save some bufs from r->in
* to a temporary file, and add them to a r->out chain
*/
rc = ngx_event_pipe_write_chain_to_temp_file(p);
ngx_log_debug1(NGX_LOG_DEBUG_EVENT, p->log, 0,
"pipe temp offset: