在kong-pongo环境测试插件时,无法读取测试用例设置的共享内存缓存
问题解决:Kong-Pongo测试中共享内存缓存无法读取
问题场景
在Kong-Pongo环境测试自定义插件时,插件通过ngx.shared.test_cache读取共享内存缓存,但测试用例中直接调用ngx.shared.test_cache:set设置的值,插件始终读取为nil,报错日志如下:
2023/06/29 10:58:51 [notice] 96#0: *150 [kong] handler.lua:23 ----------------notice-------------, client: 127.0.0.1, server: kong, request: "GET /status/200 HTTP/1.1", host: "test.com" 2023/06/29 10:58:51 [error] 96#0: *150 [kong] init.lua:354 [hello-world] /kong-plugin/kong/plugins/hello-world/handler.lua:25: attempt to concatenate local 'cached_value' (a nil value), client: 127.0.0.1, server: kong, request: "GET /status/200 HTTP/1.1", host: "test.com"
插件核心代码:
local function _find_cache(key) local cached, error = ngx.shared.test_cache:get(key) if cached then return cached,nil else return nil,error end end function _M:access(conf) klog.notice('----------------notice-------------') local cached_value = _find_cache('test') klog.notice('cached_value ' .. cached_value) end
测试用例原设置代码:
it("test cache", function() ngx.shared.test_cache:set('test', 'response_cache', tonumber(1000)-10) local res, err = client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "test.com", }, } assert.res_status(200, res) end)
原因分析
Kong-Pongo的测试代码运行在独立的Lua虚拟机(VM)中,而Kong处理请求的逻辑运行在Nginx Worker进程的Lua VM里。直接在测试用例中调用ngx.shared.test_cache:set,是在测试进程的VM中设置缓存,和插件所在的VM完全隔离,因此插件无法读取到该值。
解决方法
使用Kong测试工具提供的helpers.exec方法,在Kong的Nginx进程上下文执行Lua代码来设置缓存,确保缓存数据写入到插件所在的共享内存区中。
修改后的测试用例代码:
it("test cache", function() -- 通过helpers.exec在Kong的Nginx进程中设置缓存 helpers.exec("lua", "ngx.shared.test_cache:set('test', 'response_cache', 990)") local res, err = client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "test.com", }, } assert.res_status(200, res) end)
同时确认Kong启动配置中的nginx_http_lua_shared_dict已正确配置(当前配置无误),确保test_cache共享内存区存在:
assert(helpers.start_kong({ database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", plugins = "bundled," .. PLUGIN_NAME, nginx_http_lua_shared_dict = 'test_cache 64m', }, nil, nil))
修改后插件即可读取到测试用例中设置的缓存值。
内容的提问来源于stack exchange,提问作者user11042713
相关产品推荐
相关产品推荐

