nginx的源代码分析--间接回调机制的使用和类比

时间:2023-03-09 07:13:14
nginx的源代码分析--间接回调机制的使用和类比

nginx使用了间接回调机制。结合upstream机制的使用来说明一下,首先明白几个事实:

1)事实上ngxin和下游client的连接使用的是ngx_http_connection_t,每一个连接相应着一个读事件、一个写事件,epoll监听队列监听的是事件(ngx_event_t),可是事件的data字段相应于这个事件所属的连接(ngx-connection_t)。可是nginx和上游server之间的连接使用的ngx_peer_connection_t。事实上ngx_peer_connection_t是ngx_connection_t结构体的封装,前者包含了后者。算是后者的高级应用

2)ngx_connection_t相应nginx和client的连接。每一个这种连接都有一个请求(ngx_http_request_t)与之相相应。同一时候请求中有连个字段,write_event_handler和read_event_handler,这连个字段属于请求的读写回调,可是他非常显然不能被激活,能激活的就是读写事件(ngx_event_t)

3)在HTTP请求的后期阶段,nginx通过连接上的读写事件回调(这个已经被epoll监控)来间接调用请求上的读写回调。这么一来,假设想该变请求上的流程。仅仅须要改动

ngx_http_request_t上的read_event_handler和write_event_handler就可以。这种实现能够在ngx_http_handler函数中体现

4)nginx在处理upstream和上游的连接时,每个upstream连接(ngx_peer_connection_t)相应一个upstream机制(ngx_http_upstream_t)。由于upstream的连接也能够看成ngx-connection_t,所以和ngx_connection_t类似,ngx_http_upstream_t中也有两个字段read_event_handler和write_event-handler,这样在处理和上游的连接上的读写回调时也是间接调用了ngx_http_upstream_t的读写回调函数
这个在ngx_http_upstream_connection中能够看到 c=u->peer.connection。这里的c(ngx-connection_t)是和上游server之间的连接

c->write->hanlder = ngx_http_upstream_handler,在这一行和接下来的几行。认真阅读,会发现ngx_http_upstream_handler和ngx_http_handler有相似之处

5)这么一来,在接下来的处理中仅仅需关注ngx_http_upstream_t上的读写(write_event_handler & read_event_handler)就可以完毕nginx和上游server之间的交互,仅仅需关系ngx_http_request_t中的读写(write_event_handler & read_event_handler)就可以完毕nginx和client之间的监护

(总结:在连诶http请求和经过upstream机制的请求时,一定要明确当前的ngx_connection_t是指nginx和谁之间的连接)