为什么在Nginx上启用缓存,缓存是否会缓存dofile()变量和局部变量。

我有一个像这样的 nginx.conf:

local /api/{
    # lua_code_cache off;
    default_type application/json;
    content_by_lua_file webapi.lua;
    }

在 webapi.lua 中,我有以下代码:

require("LuaXml")
local xml = xml

function foo1(args)
     dofile(file1)
     local var = var
     xml.load(file1)
end

function foo2(args)
     dofile(file2)
     local var = var
     xml.load(file2)
end

输出结果是:

第一次请求 foo1 时,一切正常,本地变量在 file1 中有值,xml 正常工作。 第二次请求 foo2 时,本地变量被赋值为 file1 中的值,而不是 file2 中的值,而且 xml 是 nil 值,因为日志显示“尝试索引一个 nil 值”。

能有人教我吗?

点赞
用户2789404
用户2789404

这不是 ngx_lua 缓存您的 dofile 调用,而是您自己的 Lua 代码正在被加载(可能还包括您使用的第三方 Lua 模块),它正在通过创建新的 Lua 全局变量(比如全局变量 "xml")来污染 Lua 全局命名空间。请参阅以下文档了解更多细节:

https://github.com/openresty/lua-nginx-module#lua-variable-scope

2015-06-18 03:34:17