30.4 Buffering Responses

Problem

You need to buffer responses between upstream servers and clients

in memory to avoid writing responses to temporary files.

问题

将服务器对客户端的响应写入内存缓冲区而不是文件里。


Solution

Tune proxy buffer settings to allow NGINX the memory to buffer

response bodies:

server {
    proxy_buffering on;
    proxy_buffer_size 8k;
    proxy_buffers 8 32k;
    proxy_busy_buffer_size 64k;
    ...
}

The proxy_buffering directive is either on or off; by default it’s on.

The proxy_buffer_size denotes the size of a buffer used for read‐

ing the first part of the response from the proxied server and

defaults to either 4k or 8k, depending on the platform. The

proxy_buffers directive takes two parameters: the number of buf‐

fers and the size of the buffers. By default the proxy_buffers direc‐

tive is set to a number of 8 buffers of size either 4k or 8k, depending

on the platform. The proxy_busy_buffer_size directive limits the

size of buffers that can be busy, sending a response to the client

while the response is not fully read. The busy buffer size defaults to

double the size of a proxy buffer or the buffer size.

解决方案

调整代理模块的缓存区设置,允许 NGINX 服务器将响应消息体写入内存缓冲区:

server {
    proxy_buffering on;
    proxy_buffer_size 8k;
    proxy_buffers 8 32k;
    proxy_busy_buffer_size 64k;
    ...
}

proxy_buffering 值可以使 on 或 off,默认是 on。proxy_buffer_size 指令

表示用于读取来自代理服务器响应的缓冲大小,依据平台不同它的默认值为

4k 或 8k。proxy_buffers 指令包含两个值,支持的缓存区个数和单个缓存区

容量大小,默认是 8 个缓存区,依据平台不同单个缓存区默认容量为 4k 或 8k。

proxy_busy_buffer_size 指令用于配置未完全读取响应时直接响应客户端的缓冲

区大小,它的空间一般为 proxy_buffers 的两倍为最佳。


Discussion

Proxy buffers can greatly enhance your proxy performance, depend‐

ing on the typical size of your response bodies. Tuning these settings

can have adverse effects and should be done by observing the aver‐

age body size returned, and thoroughly and repeatedly testing.

Extremely large buffers set when they’re not necessary can eat up the

memory of your NGINX box. You can set these settings for specific

locations that are known to return large response bodies for optimal

performance.

结论

代理缓存能显著提升代理服务性能,这取决于响应内容的大小。开启缓冲区设置

应当仔细测试响应内容的平均大小,并进行大量测试和调试,否则可能引发副作

用。而如果将缓存区大小设置的非常大也不行,这回占用大量的 NGINX 内存。

一种方案是将缓冲区大小设置为与最大响应消息相同以提升性能。

参考

[nginx缓冲区优化](http://www.cnblogs.com/me115/p/5698787.html\

results matching ""

    No results matching ""