5.1.2 设置upstream的限制性参数

本节介绍的是ngx_http_upstream_t中的conf成员,它用于设置upstream模块处理请求时的参数,包括连接、发送、接收的超时时间等。


typedef struct{

……

//连接上游服务器的超时时间,单位为毫秒

ngx_msec_t

connect_timeout;

//发送TCP包到上游服务器的超时时间,单位为毫秒

ngx_msec_t

send_timeout;

//接收TCP包到上游服务器的超时时间,单位为毫秒

ngx_msec_t

read_timeout;

……

}ngx_http_upstream_conf_t;


ngx_http_upstream_conf_t中的参数有很多,12.1.3节会完整地介绍所有成员。事实上,HTTP反向代理模块在nginx.conf文件中提供的配置项大都是用来设置ngx_http_upstream_conf_t结构体中的成员的。上面列出的3个超时时间是必须要设置的,因为它们默认为0,如果不设置将永远无法与上游服务器建立起TCP连接(因为connect_timeout值为0)。

使用第4章介绍的14个预设方法可以非常简单地通过nginx.conf配置文件设置ngx_http_upstream_conf_t结构体。例如,可以把ngx_http_upstream_conf_t类型的变量放到ngx_http_mytest_conf_t结构体中。


typedef struct{

……

ngx_http_upstream_conf_t upstream;

}ngx_http_mytest_conf_t;


接下来以设置conn_timeout连接超时时间为例说明如何编写ngx_command_t来读取配置文件。


static ngx_command_t ngx_http_mytest_commands[]={

……

{ngx_string("upstream_conn_timeout"),

NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,

ngx_conf_set_msec_slot,

NGX_HTTP_LOC_CONF_OFFSET,

/给出conn_timeout成员在ngx_http_mytest_conf_t结构体中的偏移字节数/

offsetof(ngx_http_mytest_conf_t,upstream.conn_timeout),

NULL},

……

}


这样,nginx.conf文件中的upstream_conn_timeout配置项将被解析到ngx_http_mytest_conf_t结构体的upstream.conn_timeout成员中。在处理实际请求时,只要把ngx_http_mytest_conf_t配置项的upstream成员赋给ngx_http_upstream_t中的conf成员即可。例如,在ngx_http_mytest_handler方法中可以这样设置:


ngx_http_mytest_conf_tmycf=(ngx_http_mytest_conf_t)ngx_http_get_module_loc_conf(r,ngx_http_mytest_module);

r->upstream->conf=&mycf->upstream;


上面代码中的r->upstream->conf是必须要设置的,否则进程会崩溃(crash)。

提示 每一个请求都有独立的ngx_http_upstream_conf_t结构体,这意味着每一个请求都可以拥有不同的网络超时时间等配置,用户甚至可以根据HTTP请求信息决定连接上游服务器的超时时间、缓存上游响应包体的临时文件存放位置等,这些都只需要在设置r->upstream->conf时简单地进行赋值即可,有时这非常有用。