起因
在stream模块中,使用到了事件结构 ngx_event_t 中的 write 条目,但是一直不知道这个东西在哪设置,其什么作用。
事实上,一直以来我都有一个误区,认为 ngx_stream_proxy_process_connection() 函数的第二个参数 from_upstream 表示的是数据是否来自上游。以至于,在如下代码时,很困惑,为什么,靠一个 ev->write 就能够确定,数据是否是从上有来的呢??
static void
ngx_stream_proxy_upstream_handler(ngx_event_t *ev)
{
ngx_stream_proxy_process_connection(ev, !ev->write);
}
解析
ev->write 表示的是,当前事件是读事件还是写事件,如果是读事件,ev->write就是0;如果是写事件,ev->write就是1。在获取连接的时候,也就是在 ngx_get_connection() 函数中就已经被设置了,且自始至终,都没有被更改,因为读写事件是不会互相转换的。
在 ngx_stream_proxy_downstream_handler() 和 ngx_stream_proxy_upstream_handler() 函数中通过 ev->write 来确定ngx_stream_proxy_process_connection() 函数的第二个参数 from_upstream 的值。
实际上, from_upstream 表示的并不是事件或者数据是否来自上游,而是表示是否需要从上游读取数据。
简单来说,from_upstream的等于1,就表示需要从上有读数据,写入到下游;from_upstream等于0,就表示需要从下游读数据,写到上游。
分析如下:
下游读事件
当有数据来自客户端,也就是 ngx_stream_proxy_downstream_handler() 函数触发读事件,
ngx_stream_proxy_downstream_handler() 函数中有如下处理:
static void
ngx_stream_proxy_downstream_handler(ngx_event_t *ev)
{
ngx_stream_proxy_process_connection(ev, ev->write);
}
此时,ev->write就是0,所以调用 ngx_stream_proxy_process() 函数时,传入的参数就是 ngx_stream_proxy_process(s, 0, 0);
from_upstream 为0,表示从下游读数据;do_write 为0,表示先读后写。
所以,在 ngx_stream_proxy_process() 函数中,就会首先读取下游数据,然后发送到上游。
下游写事件
当客户端产生可写事件时,也就是 ngx_stream_proxy_downstream_handler() 函数触发写事件,
此时,ev->write就是1,所以调用 ngx_stream_proxy_process() 函数时,传入的参数就是 ngx_stream_proxy_process(s, 1, 1);
from_upstream 为1,表示从上游读数据;do_write 为1,表示先写后读。
所以,在 ngx_stream_proxy_process() 函数中,首先将上游数据写入到下游,然后再从上游读取数据,发送到下游。
上游读事件
当有数据来自服务端,也即是 ngx_stream_proxy_upstream_handler() 函数触发读事件,
ngx_stream_proxy_upstream_handler() 函数中有如下处理:
static void
ngx_stream_proxy_upstream_handler(ngx_event_t *ev)
{
ngx_stream_proxy_process_connection(ev, !ev->write);
}
此时,ev->write就是0, 所以调用 ngx_stream_proxy_process() 函数时,传入的参数就是 ngx_stream_proxy_process(s, 1, 0);
from_upstream 为1,表示从上游读数据;do_write 为0,表示先读后写。
所以,在 ngx_stream_proxy_process() 函数中,首先将上游数据进行读取,然后发送到下游。
上游写事件
当服务端产生可写事件时,也就是 ngx_stream_proxy_upstream_handler() 函数触发写事件,
此时,ev->write就是1, 所以调用 ngx_stream_proxy_process() 函数时,传入的参数就是 ngx_stream_proxy_process(s, 0, 1);
from_upstream 为0,表示从下游读数据;do_write 为1,表示先写后读。
所以,在 ngx_stream_proxy_process() 函数中,首先将下游数据写入到上游,然后再从下游读取数据,发送到上游。