ngx.location.capture

用法:

local res = ngx.location.capture(uri, options)

发起一个同步非阻塞的nginx子请求,uri是internal的。

返回的res是个table,索引依次是status(值是number类型)、body(值是string类型)、header(值是table类型)、truncated(值是boolean类型)

context: rewrite_by_lua*, access_by_lua*, content_by_lua*

Issues a synchronous but still non-blocking Nginx Subrequest using uri.

Nginx's subrequests provide a powerful way to make non-blocking internal requests to other locations configured with disk file directory or any other nginx C modules like ngx_proxyngx_fastcgingx_memcngx_postgresngx_drizzle, and even ngx_lua itself and etc etc etc.

Also note that subrequests just mimic the HTTP interface but there is no extra HTTP/TCP traffic nor IPC involved. Everything works internally, efficiently, on the C level.

Subrequests are completely different from HTTP 301/302 redirection (via ngx.redirect) and internal redirection (via ngx.exec).

You should always read the request body (by either calling ngx.req.read_body or configuring lua_need_request_body on) before initiating a subrequest.

This API function (as well as ngx.location.capture_multi) always buffers the whole response body of the subrequest in memory. Thus, you should use cosockets and streaming processing instead if you have to handle large subrequest responses.

Here is a basic example:

 res = ngx.location.capture(uri)

Returns a Lua table with 4 slots: res.statusres.headerres.body, and res.truncated.

res.status holds the response status code for the subrequest response.

res.header holds all the response headers of the subrequest and it is a normal Lua table. For multi-value response headers, the value is a Lua (array) table that holds all the values in the order that they appear. For instance, if the subrequest response headers contain the following lines:

 Set-Cookie: a=3
Set-Cookie: foo=bar
Set-Cookie: baz=blah

Then res.header["Set-Cookie"] will be evaluated to the table value {"a=3", "foo=bar", "baz=blah"}.

res.body holds the subrequest's response body data, which might be truncated. You always need to check the res.truncated boolean flag to see if res.body contains truncated data. The data truncation here can only be caused by those unrecoverable errors in your subrequests like the cases that the remote end aborts the connection prematurely in the middle of the response body data stream or a read timeout happens when your subrequest is receiving the response body data from the remote.

URI query strings can be concatenated to URI itself, for instance,

 res = ngx.location.capture('/foo/bar?a=3&b=4')

Named locations like @foo are not allowed due to a limitation in the nginx core. Use normal locations combined with the internal directive to prepare internal-only locations.

An optional option table can be fed as the second argument, which supports the options:

  • method specify the subrequest's request method, which only accepts constants like ngx.HTTP_POST.
  • body specify the subrequest's request body (string value only).
  • args specify the subrequest's URI query arguments (both string value and Lua tables are accepted)
  • ctx specify a Lua table to be the ngx.ctx table for the subrequest. It can be the current request's ngx.ctx table, which effectively makes the parent and its subrequest to share exactly the same context table. This option was first introduced in the v0.3.1rc25 release.
  • vars take a Lua table which holds the values to set the specified Nginx variables in the subrequest as this option's value. This option was first introduced in the v0.3.1rc31 release.
  • copy_all_vars specify whether to copy over all the Nginx variable values of the current request to the subrequest in question. modifications of the nginx variables in the subrequest will not affect the current (parent) request. This option was first introduced in the v0.3.1rc31 release.
  • share_all_vars specify whether to share all the Nginx variables of the subrequest with the current (parent) request. modifications of the Nginx variables in the subrequest will affect the current (parent) request. Enabling this option may lead to hard-to-debug issues due to bad side-effects and is considered bad and harmful. Only enable this option when you completely know what you are doing.
  • always_forward_body when set to true, the current (parent) request's request body will always be forwarded to the subrequest being created if the body option is not specified. The request body read by either ngx.req.read_body() or lua_need_request_body on will be directly forwarded to the subrequest without copying the whole request body data when creating the subrequest (no matter the request body data is buffered in memory buffers or temporary files). By default, this option is false and when the body option is not specified, the request body of the current (parent) request is only forwarded when the subrequest takes the PUT or POST request method.

Issuing a POST subrequest, for example, can be done as follows

 res = ngx.location.capture(
'/foo/bar',
{ method = ngx.HTTP_POST, body = 'hello, world' }
)

See HTTP method constants methods other than POST. The method option is ngx.HTTP_GET by default.

The args option can specify extra URI arguments, for instance,

 ngx.location.capture('/foo?a=1',
{ args = { b = 3, c = ':' } }
)

is equivalent to

 ngx.location.capture('/foo?a=1&b=3&c=%3a')

that is, this method will escape argument keys and values according to URI rules and concatenate them together into a complete query string. The format for the Lua table passed as the args argument is identical to the format used in the ngx.encode_args method.

The args option can also take plain query strings:

 ngx.location.capture('/foo?a=1',
{ args = 'b=3&c=%3a' } }
)

This is functionally identical to the previous examples.

The share_all_vars option controls whether to share nginx variables among the current request and its subrequests. If this option is set to true, then the current request and associated subrequests will share the same Nginx variable scope. Hence, changes to Nginx variables made by a subrequest will affect the current request.

Care should be taken in using this option as variable scope sharing can have unexpected side effects. The argsvars, or copy_all_vars options are generally preferable instead.

This option is set to false by default

 location /other {
set $dog "$dog world";
echo "$uri dog: $dog";
} location /lua {
set $dog 'hello';
content_by_lua_block {
res = ngx.location.capture("/other",
{ share_all_vars = true }); ngx.print(res.body)
ngx.say(ngx.var.uri, ": ", ngx.var.dog)
}
}

Accessing location /lua gives

/other dog: hello world
/lua: hello world

The copy_all_vars option provides a copy of the parent request's Nginx variables to subrequests when such subrequests are issued. Changes made to these variables by such subrequests will not affect the parent request or any other subrequests sharing the parent request's variables.

 location /other {
set $dog "$dog world";
echo "$uri dog: $dog";
} location /lua {
set $dog 'hello';
content_by_lua_block {
res = ngx.location.capture("/other",
{ copy_all_vars = true }); ngx.print(res.body)
ngx.say(ngx.var.uri, ": ", ngx.var.dog)
}
}

Request GET /lua will give the output

/other dog: hello world
/lua: hello

Note that if both share_all_vars and copy_all_vars are set to true, then share_all_vars takes precedence.

In addition to the two settings above, it is possible to specify values for variables in the subrequest using the vars option. These variables are set after the sharing or copying of variables has been evaluated, and provides a more efficient method of passing specific values to a subrequest over encoding them as URL arguments and unescaping them in the Nginx config file.

 location /other {
content_by_lua_block {
ngx.say("dog = ", ngx.var.dog)
ngx.say("cat = ", ngx.var.cat)
}
} location /lua {
set $dog '';
set $cat '';
content_by_lua_block {
res = ngx.location.capture("/other",
{ vars = { dog = "hello", cat = 32 }}); ngx.print(res.body)
}
}

Accessing /lua will yield the output

dog = hello
cat = 32

The ctx option can be used to specify a custom Lua table to serve as the ngx.ctx table for the subrequest.

 location /sub {
content_by_lua_block {
ngx.ctx.foo = "bar";
}
}
location /lua {
content_by_lua_block {
local ctx = {}
res = ngx.location.capture("/sub", { ctx = ctx }) ngx.say(ctx.foo);
ngx.say(ngx.ctx.foo);
}
}

Then request GET /lua gives

bar
nil

It is also possible to use this ctx option to share the same ngx.ctx table between the current (parent) request and the subrequest:

 location /sub {
content_by_lua_block {
ngx.ctx.foo = "bar";
}
}
location /lua {
content_by_lua_block {
res = ngx.location.capture("/sub", { ctx = ngx.ctx })
ngx.say(ngx.ctx.foo);
}
}

Request GET /lua yields the output

bar

Note that subrequests issued by ngx.location.capture inherit all the request headers of the current request by default and that this may have unexpected side effects on the subrequest responses. For example, when using the standard ngx_proxymodule to serve subrequests, an "Accept-Encoding: gzip" header in the main request may result in gzipped responses that cannot be handled properly in Lua code. Original request headers should be ignored by setting proxy_pass_request_headersto off in subrequest locations.

When the body option is not specified and the always_forward_body option is false (the default value), the POST and PUTsubrequests will inherit the request bodies of the parent request (if any).

There is a hard-coded upper limit on the number of concurrent subrequests possible for every main request. In older versions of Nginx, the limit was 50 concurrent subrequests and in more recent versions, Nginx 1.1.x onwards, this was increased to 200 concurrent subrequests. When this limit is exceeded, the following error message is added to the error.log file:

[error] 13983#0: *1 subrequests cycle while processing "/uri"

The limit can be manually modified if required by editing the definition of the NGX_HTTP_MAX_SUBREQUESTS macro in the nginx/src/http/ngx_http_request.h file in the Nginx source tree.

Please also refer to restrictions on capturing locations configured by subrequest directives of other modules.

lua-nginx-module模块常用命令的更多相关文章

  1. 用lua nginx module搭建一个二维码

    用lua nginx module搭建一个二维码(qr code)生成器 作者 vinoca 發布於 2014年10月31日 如果有VPS,或者开源的路由器,安装一个nginx,添加lua-nginx ...

  2. nginx 配置以及常用命令

    windows下安装以及配置nginx http://jingyan.baidu.com/article/f3e34a12a9c1c3f5eb6535d4.html 1)下载地址: http://ng ...

  3. nginx日常维护常用命令

    http://www.jb51.net/article/47750.htm 一.简明nginx常用命令 1. 启动 Nginx poechant@ubuntu:sudo ./sbin/nginx 2. ...

  4. npm 模块常用命令

    mocha mocha --compilers js:babel/register : 在babel模式下测试,默认查找test文件夹,注意此时全局不要安装babel; ./node_modules/ ...

  5. Nginx安装及常用命令

    一.选定源码目录 cd /usr/local/src 可以是任何目录,本文选定的是/usr/local/src 二.安装依赖库 yum install gcc yum install pcre-dev ...

  6. nginx实战操作(常用命令及配置)

    1. nginx介绍 2. nginx常用命令 验证配置是否正确: nginx -t 查看Nginx的详细的版本号:nginx -V 查看Nginx的简洁版本号:nginx -v 启动Nginx:st ...

  7. 【Nginx】Linux常用命令------启动、停止、重启

    启动 启动代码格式:nginx安装目录地址 -c nginx配置文件地址 例如: [root@LinuxServer sbin]# /usr/local/nginx/sbin/nginx -c /us ...

  8. python os模块 常用命令

    python编程时,经常和文件.目录打交道,这是就离不了os模块.os模块包含普遍的操作系统功能,与具体的平台无关.以下列举常用的命令 1. os.name()——判断现在正在实用的平台,Window ...

  9. 【python】os模块常用命令

    python编程时,经常和文件.目录打交道,这是就离不了os模块.os模块包含普遍的操作系统功能,与具体的平台无关.以下列举常用的命令 1. os.name()——判断现在正在实用的平台,Window ...

  10. python os模块常用命令

    python编程时,经常和文件.目录打交道,这是就离不了os模块.os模块包含普遍的操作系统功能,与具体的平台无关.以下列举常用的命令 1. os.name()——判断现在正在实用的平台,Window ...

随机推荐

  1. HDU 3361 ASCII (水题)

    题意: 析:不说话. #include <cstdio> #include <string> #include <cstdlib> #include <cma ...

  2. toolbox类

    新建Qt  应用,项目名称为“c”,基类选择“QWidget”,取消“创建界面”复选框的选中状态. 添加该工程的提供主要显示界面的函数所在的文件,在“c”项目名上单击鼠标右键,在弹出的快捷菜单中选择“ ...

  3. Cannot evaluate the property expression "$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\Microsoft.Cpp\v4.0\V140\'))" found at "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuil

    Cannot evaluate the property expression "$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBu ...

  4. Mybatis 多个Mapper

    在实际应用中的,会有较多个mapper.如果每新建一个mapper,就向SqlMapConfig上加上对应的配置文件,会十分不便. 可以新建一个package,在其下面放置Mapper.java,同时 ...

  5. javascript 如何创建只能执行一次的事件。

    document.getElementById("myelement").addEventListener("click", handler);   // ha ...

  6. C#设计模式系列:代理模式(Proxy Pattren)

    一.引言 在软件开发过程中,有些对象有时候会由于网络或者其他的障碍,以至于不能够或者不能直接访问到这些对象,如果直接访问对象给系统带来不必要的复杂性,这时候可以在客户端和目标对象之间增加一层中间层,让 ...

  7. WinForm心得

    如果有UI部分可以复用,那么可以单独设置为一个UserControl或者一个自定义子类控件 如果是单一一个控件,只是继承并修改了默认控件的样式行为,那么可以直接创建一个class并继承该控件,缺点是D ...

  8. python学习之路 三:字符编码

    本节重点 彻底掌握字符编码之前的转换关系 掌握 python2 vs python3 上编码的区别 掌握 python2 和python3 上bytes,str 的区别 补充知识点:三元运算 ​三元运 ...

  9. 通过api获取句柄控制其他窗体

    很多时候,编写程序模拟鼠标和键盘操作可以方便的实现你需要的功能,而不需要对方程序为你开放接口.比如,操作飞信定时发送短信等.我之前开发过飞信耗子,用的是对飞信协议进行抓包,然后分析协议,进而模拟协议的 ...

  10. Notes on view-dependent Catmull-Clark subdivision surfaces

    - Since we perform elimination after every step of subdivision, the only hanging nodes that we encou ...