hi,春哥各位openresty使用者,我现在有这个一个业务场景问题想指教下,我页面每请求一次的时候就会往redis里面rpush一条数据,这样redis客户端连接数据数会巨大,现在我想使用您提供的这个lrucache,将数据存在缓存在一个key中,等到10条或者更多条的数据再去连接redis,将数据推入redis进行处理减少redis客户端连接数。但是现在线上环境并发量巨大,我每次插入数据时都会判断数组长度,我记录日志发现长度会远远大于我设置的值(10条或者多条),然后push到redis里面的包也会有好几M,同时cjson里面的encode方法也会提示内存报错(应该是缓存里面的长度太大导致),请问下现在有没有好的解决方案?或者能够加锁解决呢(lua-resty-lock这个模块只针对初始化数据字典 ngx.shared.DICT有效)?
local json = require "cjson.safe"
local lrucache = require "resty.lrucache"
-- openresty内存
local c = lrucache.new(10)
if not c then
return error("failed to create the cache: " .. (err or "unknown"))
end
local function writeToRedis(data)
--将数据写入redis
end
-- data 是一个组装好的数据table {0={}}
local function test(data)
-- 1.查询缓存长度
local lcache = c:get('test_key') or {}
-- 单条记录插入缓存
if table.getn(data) == 1 then
table.insert(lcache, data[1])
c:set('test_key', lcache)
else
-- 数据大于1条时直接写入redis
local res = writeToRedis(data)
-- 将数据写入redis
if not res then
return nil
end
return true
end
-- 2.从缓存获取长度
local lcachelen = table.getn(lcache)
ngx.log(ngx.INFO, 'cache length is :' .. lcachelen) -- 日志记录中发现这个长度远远大于10(我在本地压测时能够达到4,5千的长度)
if lcachelen >= 10 then
local cacheData = json.encode(lcache) --这个解析时也会出现内存错误
if not cacheData then
ngx.log(ngx.ERR, 'cache value is nil:' .. cacheData)
return nil
end
local res = writeToRedis(cacheData)
-- 将数据写入redis
if not res then
return nil
end
--数据打入成功后,删除缓存
c:delete('test_key')
end
return true
end