Openresty在请求处理的多个阶段内数据共享

429次阅读
没有评论

共计 721 个字符,预计需要花费 2 分钟才能阅读完成。

Openresty在请求处理的多个阶段内数据共享

在nginx/openresty中,我们知道可以通过worker_processes参数控制work进程,worker进程用来处理请求,而master进程只有一个负责调度和加载配置等

在openresty中若要在请求worker处理的不同阶段进行数据共享,可以通过一个ngx.ctx的table来完成。示例如下:

location /test {
     rewrite_by_lua_block {
         ngx.ctx.foo = 76
     }
     access_by_lua_block {
         ngx.ctx.foo = ngx.ctx.foo + 3
     }
     content_by_lua_block {
         ngx.say(ngx.ctx.foo)
     }
 }

但是注意其生命周期与当前请求相同,不能跨请求共享(a请求用不了b请求过程中产生的数据),因为每个请求/子请求都有自己的ngx.ctx表,样例如下:

 location /sub {
     content_by_lua_block {
         ngx.say("sub pre: ", ngx.ctx.blah)
         ngx.ctx.blah = 32
         ngx.say("sub post: ", ngx.ctx.blah)
     }
 }

 location /main {
     content_by_lua_block {
         ngx.ctx.blah = 73
         ngx.say("main pre: ", ngx.ctx.blah)
         local res = ngx.location.capture("/sub")
         ngx.print(res.body)
         ngx.say("main post: ", ngx.ctx.blah)
     }
 }

最终输出如下

 main pre: 73
 sub pre: nil
 sub post: 32
 main post: 73

学习参考手册:

正文完
 
xadocker
版权声明:本站原创文章,由 xadocker 2021-07-11发表,共计721字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)