当需要访问第三方服务时,Nginx提供了两种全异步方式来与第三方服务器通信:upstream与subrequest。本文将介绍upstream的使用方式,Nginx的HTTP反向代理模块就是基于upstream方式实现,当我们希望把第三方服务的内容几乎原封不懂地返回给用户时,一般使用upstream方式,它可以非常高效地透传HTTP。
1.upstream的使用方式 |
upstream的使用方式并不复杂,它提供了8个回调方法,见文件http/ngx_http_upstream_t.h
,用户需要实现的其中的几个回调方法,本例中实现了3个回调方法:
struct ngx_http_upstream_s{
//...
//构造发往上游服务器的请求
ngx_int_t (*create_request)(ngx_http_request_t *r);
//收到上游服务器的TCP流时回调,直到不返回NGX_AGAIN,处理http响应
ngx_int_t (*process_header)(ngx_http_request_t *r);
//销毁upstream时回调
void (*finalize_request)(ngx_http_request_t *r,ngx_int_t rc);
//...
};
那么upstream是如何嵌入到一个请求中的?
模块在处理任何一个请求时都有ngx_http_request_t
结构对象r
,该结构中有一个ngx_http_upstream_t
类型的成员upstream
,见文件http/ngx_http_request.h
struct ngx_http_request_s
{
//...
ngx_http_upstream_t *upstream;
//...
}
如果没有使用upstream机制,则需要将相应的成员设置为NULL指针,否则需要对r->upstream
进行设置。
HTTP模块启用upstream机制的步骤如下:
使用upstream模块提供的ngx_http_upstream_init方法后,HTTP如何运行upstream框架,大致流程如下: