共计 2681 个字符,预计需要花费 7 分钟才能阅读完成。
记录下openresty处理流程,方便后续学习使用
- init阶段
- init_by_lua:运行在Nginx loading-config 阶段,注册Nginx Lua全局变量,和一些预加载模块。是Nginx master进程在加载Nginx配置时执行
- init_worker_by_lua:在Nginx starting-worker阶段,即每个nginx worker启动时会调用,通常用来hook worker进程,并创建worker进行的计时器,用来健康检查,或者设置熔断记时窗口等等
- rewrite/access阶段
- access_by_lua:在access tail阶段,用来对每次请求做访问控制,权限校验等等,能拿到很多相关变量。例如:请求体中的值,header中的值,可以将值添加到ngx.ctx, 在其他模块进行相应的控制
- set_by_lua:流程分支处理判断变量初始化
- rewrite_by_lua:转发、重定向、缓存等功能(例如特定请求代理到外网)
- content阶段
- content_by_lua:内容生成,对于每个api请求进行处理,注意不能与proxy_pass放在同一个location下
- balancer_by_lua:可以实现不同的负载均衡策略,并调用set_current_peer函数设置当前query调用的backend
- header_filter_by_lua: 在output-header-filter阶段,通常用来重新响应头部,设置cookie等,也可以用来作熔断触发标记
- body_filter_by_lua:应答 BODY 过滤处理(例如完成应答内容统一成大写)
- log阶段
- log_by_lua:记录日志,记录一下整个请求的耗时,状态码等
一个样例
location /mixed {
set_by_lua_block $a {
ngx.log(ngx.ERR, "set_by_lua*")
}
rewrite_by_lua_block {
ngx.log(ngx.ERR, "rewrite_by_lua*")
}
access_by_lua_block {
ngx.log(ngx.ERR, "access_by_lua*")
}
content_by_lua_block {
ngx.log(ngx.ERR, "content_by_lua*")
}
header_filter_by_lua_block {
ngx.log(ngx.ERR, "header_filter_by_lua*")
}
body_filter_by_lua_block {
ngx.log(ngx.ERR, "body_filter_by_lua*")
}
log_by_lua_block {
ngx.log(ngx.ERR, "log_by_lua*")
}
}
在error.log中查看调试输出
2021/03/26 02:12:58 [error] 5561#0: *1 [lua] set_by_lua:2: set_by_lua*, client: 192.168.44.145, server: openresty.xadocker.cn, request: "GET /mixed HTTP/1.1", host: "openresty.xadocker.cn"
2021/03/26 02:12:58 [error] 5561#0: *1 [lua] rewrite_by_lua(openresty.xadocker.cn.conf:254):2: rewrite_by_lua*, client: 192.168.44.145, server: openresty.xadocker.cn, request: "GET /mixed HTTP/1.1", host: "openresty.xadocker.cn"
2021/03/26 02:12:58 [error] 5561#0: *1 [lua] access_by_lua(openresty.xadocker.cn.conf:257):2: access_by_lua*, client: 192.168.44.145, server: openresty.xadocker.cn, request: "GET /mixed HTTP/1.1", host: "openresty.xadocker.cn"
2021/03/26 02:12:58 [error] 5561#0: *1 [lua] content_by_lua(openresty.xadocker.cn.conf:260):2: content_by_lua*, client: 192.168.44.145, server: openresty.xadocker.cn, request: "GET /mixed HTTP/1.1", host: "openresty.xadocker.cn"
2021/03/26 02:12:58 [error] 5561#0: *1 [lua] header_filter_by_lua:2: header_filter_by_lua*, client: 192.168.44.145, server: openresty.xadocker.cn, request: "GET /mixed HTTP/1.1", host: "openresty.xadocker.cn"
2021/03/26 02:12:58 [error] 5561#0: *1 [lua] body_filter_by_lua:2: body_filter_by_lua*, client: 192.168.44.145, server: openresty.xadocker.cn, request: "GET /mixed HTTP/1.1", host: "openresty.xadocker.cn"
2021/03/26 02:12:58 [error] 5561#0: *1 [lua] log_by_lua(openresty.xadocker.cn.conf:269):2: log_by_lua* while logging request, client: 192.168.44.145, server: openresty.xadocker.cn, request: "GET /mixed HTTP/1.1", host: "openresty.xadocker.cn"
不同的阶段,有不同的处理行为,这是 OpenResty 的一大特色,同样这也是nginx module对外开放的处理阶段。所以对上面的流程图每个阶段多学学,多实操,适应它你就熟了,在实践中所产生的记忆比你背八股文好!
学习参考手册:
正文完