JAVA全系列 教程
3762个小节阅读:7092.1k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
子请求方式使用的函数是ngx .location.capture 在调用前必须预先在配置文件里配置好它将 "捕获" 的 location。location内部通常使用的是各种反向代理模块,利用" xxx pass " 访问后端服务。
受nginx平台限制,ngx.localtion.capture 只能用在“rewrite_by_lua” '"access_by_lua" 和"content_by_lua" 这三个执行阶段。
ngx.location.capture 的形式是:
xxxxxxxxxx
res = ngx.location.capture (uri , options) --发起子请求调用
它“ 调用 ”本 server 内的名为 "uri " 的 location ,第二个参数是可选的,以表的方传递发起子请求时的额外数据,并 以改写原始 请求信息。表里 字段有:
函数执行后会同步非阻塞地等待请求执行完毕,最后返回一个表,包含四个字段:
xxxxxxxxxx
local res = ngx.location.capture (uri, -- 发起一个子请求
{method = ngx.HTTP_POST , -- 修改子请求的方法 可以改成post
args = { ... }, -- 请求参数
body = ... -- 添加请求体
})
if res.status = ngx.HTTP_OK then --检查子请求的状态码
ngx.print(res.body) -- 获取响应体数据任意处理完毕
end
xxxxxxxxxx
location /hello {
proxy_set_header Host $host;
proxy_pass http://192.168.66.10:8080/hello;
}
location /test01 {
content_by_lua_file service/http/http_example.lua;
}
http_example.lua
xxxxxxxxxx
local capture = ngx.location.capture
local res = capture("/hello")
if res.status ~= ngx.HTTP_OK then
ngx.exit(res.status)
end
if res.truncated then
ngx.log (ngx.ERR,"XXX")
end
ngx.say(res.body)
首先,它的扩展性不够灵活,如果要访问新的后端必须要改写配置文件,配置新的locatio 口。而且,如果后端服务没有对应的 Nginx模块就需要使用 语言开发,而C语言的开发难度高、周期长是众所周知的,这就限制了 ngx.location.capture 用范围.其次, ngx.location.capture 使用的子请求机制会“完整”地捕获全部响应内容,需要使用较大的缓冲区,如果响应内容很多会造成大 内存占用, 良费系统资源.
建议尽量不使用口ngx.location.capture ,而是改用 cosocket ,它的底层运行机制与ngx .location capture 基本相同,但成本更低,更灵活可控。