openresty 1.27.1.2 获取map中某个key结果异常

29 views
Skip to first unread message

Ryan Li

unread,
Jul 22, 2025, 7:09:55 AMJul 22
to open...@googlegroups.com
操作系统:
  1. rocky 9.6  通过openresty提供的repo进行安装,openresty版本: 1.27.1.2
  2. 容器运行,openresty版本: 1.27.1.2

故障现象:
 在nginx.conf中如果 worker_processes配置为1,一直未发现问题。当worker_processes配置为auto时,在多核处理器的环境下, static_appname = _M.static_tokens[token] 这个指令的结果非常不稳定。

针对同一个token,static_appname有时一直有数据返回, 但有时一直没有数据返回。重启openresty也是同样的问题,有时重启结果正常,有时重启结果异常。

谢谢!

关键代码节选:
local _M = {}
_M.static_tokens = {}

local function load_static_tokens()
-- 从外部json文件加载数据保存到 _M.static_tokens map中
end

function _M.process()
local token = ngx.var.arg_token
if not token or token == "" then
return send_unauthorized("token is required")
end

-- 1. 检查静态 Token
local static_appname = _M.static_tokens[token]
if static_appname then
ngx.req.set_header("X-Account-Type", static_appname)
_M.metric_requests:inc(1, { "static_hit", static_appname })
return
end

-- 2. Token 格式校验
local match, err = ngx.re.match(token, config.validation.token_regex, "o")
if not match then
_M.metric_requests:inc(1, { "invalid_format", "invalid" })
return send_unauthorized()
end
end

Junlong li

unread,
Jul 22, 2025, 9:33:48 AMJul 22
to openresty
你有没有怀疑你的加载带有有问题?

ryan....@gmail.com

unread,
Jul 22, 2025, 10:07:18 PMJul 22
to openresty
你说的加载具体是指哪一部分,下面是从外部文件加载的函数,以及外部文件的内容

local function load_static_tokens()
    local file, err = io.open(config.static_tokens.file_path, "r")
    if not file then
        ngx.log(ngx.WARN, "static token file not found or could not be opened: ", config.static_tokens.file_path, " | error: ", err)
        return false
    end
 
    local content = file:read("*a")
    file:close()

local ok, data = pcall(cjson.decode, content)
if not ok or type(data) ~= "table" then
ngx.log(ngx.ERR, "failed to decode static token file: ", config.static_tokens.file_path, " | error: ", tostring(data))
return false
end

_M.static_tokens = data

local count = 0
for _ in pairs(_M.static_tokens) do count = count + 1 end
ngx.log(ngx.INFO, "successfully loaded/reloaded ", count, " static tokens from file: ", config.static_tokens.file_path)
return true
end

cat static_tokens.json
{
"e945d7d9-9e6e-4721-922a-7251a9d321d0-1678159756805": "internal",
"c5e6d492-baed-40bf-9b27-93119d2d3a0d-1689232838129": "internal"

ryan....@gmail.com

unread,
Jul 22, 2025, 10:42:58 PMJul 22
to openresty
不好意思,是自己的代码实现问题,代码在init_workder阶段加了个worker_id判断,导致这个静态token只在其中一个worker上加载了。 所以worker_processes设置为1时正常,设置为auto时就不稳定。 谢谢了
Reply all
Reply to author
Forward
0 new messages