DEBUG.WIKI
ZgoCloud:多地区部署,按需选节点;日本、美国、香港、德国
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS
晚安云;香港 CN2 ¥15/月

解决 OpenResty 报错 no memory in lua_shared_dict 共享内存耗尽修复

排查 OpenResty 网关在高并发时日志报错 no memory in lua_shared_dict,分析 共享字典空间耗尽与 set / safe_set 策略。

问题现象

OpenResty 网关处理高频缓存或限流请求时,error.log 密集打印错误:

[error] 24102#24102: *120531 lua entry thread aborted: runtime error: [string "content_by_lua"]:14: no memory in lua_shared_dict: my_cache, client: 10.0.1.20, server: api.local

触发根因

  1. 配置的 lua_shared_dict 字典容量过小,缓存数据量超过申请的物理共享内存上限;
  2. 业务代码使用了 dict:safe_set() 而未对返回值 err == 'no memory' 进行妥善降级处理;
  3. 未设置过期时间(TTL)导致非关键键持续累积占满字典,阻止了有效缓存的写入。

解决步骤

在 Nginx 配置中扩容共享字典大小

在 http 块中将分配容量适度调大:

http {
    # 将 10m 扩容为 128m
    lua_shared_dict my_cache 128m;
    lua_shared_dict ip_rate_limits 64m;
}

优化 Lua 写入策略并处理内存耗尽异常

改用带有 LRU 淘汰机制的 set() 或捕获 safe_set() 返回值:

local cache = ngx.shared.my_cache
-- 使用 set 会自动利用 LRU 机制淘汰旧键
local success, err, forcible = cache:set(key, value, 300)
if not success then
    ngx.log(ngx.WARN, "Failed to write key to shared dict: ", err)
end
if forcible then
    ngx.log(ngx.INFO, "Valid items were forcibly evicted by LRU")
end

定期监控共享内存实际使用率

利用 ngx.shared.DICT:capacity() 和 free_space() 暴露监控指标:

local free_bytes = cache:free_space()
local total_bytes = cache:capacity()
ngx.say(string.format("Usage: %.2f%%", (total_bytes - free_bytes) / total_bytes * 100))

验证确认

重载 Nginx 配置并压测:

sudo openresty -t && sudo openresty -s reload

网关错误日志恢复清零,高并发写入触发自动 LRU 淘汰,不再出现中断报错。