OpenResty中使用lua-resty-radixtree遇API禁用错误求助
OpenResty中lua-resty-radixtree报"API disabled in the current context"错误排查
错误信息
ERROR: /usr/local/openresty/luajit/share/lua/5.1/resty/expr/v1.lua:319: API disabled in the current context stack traceback: /usr/local/openresty/lualib/resty/core/var.lua:103: in function '__index' /usr/local/openresty/luajit/share/lua/5.1/resty/expr/v1.lua:319: in function 'eval' ...local/openresty/luajit/share/lua/5.1/resty/radixtree.lua:579: in function 'match_route_opts' ...local/openresty/luajit/share/lua/5.1/resty/radixtree.lua:642: in function 'match_route' ...local/openresty/luajit/share/lua/5.1/resty/radixtree.lua:675: in function 'match' lua/hello.lua:30: in function 'file_gen' init_worker_by_lua:45: in function <init_worker_by_lua:43> [C]: in function 'xpcall' init_worker_by_lua:52: in function <init_worker_by_lua:50>
相关配置文件
nginx.conf
pid logs/nginx.pid; worker_processes 1; events { worker_connections 1024; } http { server { listen 8080; location / { content_by_lua_file lua/hello.lua; } } }
hello.lua
ngx.say("Hello user!") local radix = require("resty.radixtree") local rx = radix.new({ { paths = { "/aa", "/bb*", "/name/:name/*other" }, hosts = { "*.bar.com", "foo.com" }, methods = { "GET", "POST", "PUT" }, remote_addrs = { "127.0.0.1", "192.168.0.0/16", "::1", "fe80::/32" }, vars = { { "arg_name", "==", "json" }, { "arg_weight", ">", 10 }, }, filter_fun = function(vars, opts) return vars["arg_name"] == "json" end, metadata = "metadata /bb", } }) -- try to match local opts = { host = "foo.com", method = "GET", remote_addr = "127.0.0.1", vars = ngx.var, } ngx.say(rx:match("/aa", opts)) -- try to match and store the cached value local opts = { host = "foo.com", method = "GET", remote_addr = "127.0.0.1", vars = ngx.var, matched = {} } ngx.say(rx:match("/name/json/foo/bar/gloo", opts)) ngx.say("name: ", opts.matched.name, " other: ", opts.matched.other)
问题原因
- 错误栈显示代码实际在
init_worker_by_lua阶段执行,但该阶段属于非请求上下文,无法访问ngx.var这类请求相关API。 ngx.var是请求级别的变量,仅能在请求处理阶段(如content_by_lua、access_by_lua等)使用,init_worker阶段是worker进程启动时的初始化逻辑,没有请求上下文,调用ngx.var会触发该错误。- 你提供的nginx.conf配置是用
content_by_lua_file执行hello.lua,但错误栈显示实际运行时代码被init_worker_by_lua调用,存在配置不一致的情况。
解决方法
- 确保hello.lua仅在请求处理阶段执行:保持nginx.conf中
content_by_lua_file lua/hello.lua的配置,检查是否有其他地方(如init_worker_by_lua)误引用了该文件。 - 拆分代码逻辑:如果需要提前初始化radixtree,可以将
radix.new()放在init_by_lua或init_worker_by_lua中,但rx:match()方法必须放在请求处理阶段执行,不能在init_worker阶段调用。 - 核对实际运行的Nginx配置,确认没有错误地将hello.lua挂载到
init_worker_by_lua指令下。
内容的提问来源于stack exchange,提问作者Navendu Pottekkat
相关产品推荐
相关产品推荐

