【问题标题】:why doesn't resty.redis work with the ngx.timer?为什么 resty.redis 不能与 ngx.timer 一起工作?
【发布时间】:2021-04-29 21:01:21
【问题描述】:

我已经问过here,但我想我也会在 SO 上发帖:

鉴于此代码:

local redis = require('resty.redis')

local client = redis:new()
client:connect(host,port)
ngx.thread.spawn(function()
  ngx.say(ngx.time(),' ',#client:keys('*'))
end)
ngx.timer.at(2,function()
  ngx.say(ngx.time(),' ',#client:keys('*'))
end)

我收到此错误:

---urhcdhw2pqoz---
1611628086 5
2021/01/26 10:28:08 [error] 4902#24159: *4 lua entry thread aborted: runtime error: ...local/Cellar/openresty/1.19.3.1_1/lualib/resty/redis.lua:349: bad request
stack traceback:
coroutine 0:
    [C]: in function 'send'
    ...local/Cellar/openresty/1.19.3.1_1/lualib/resty/redis.lua:349: in function 'keys'
    ./src/main.lua:20: in function <./src/main.lua:19>, context: ngx.timer

所以似乎线程可以与 redis 一起使用,但计时器不能。这是为什么呢?

【问题讨论】:

    标签: nginx lua openresty


    【解决方案1】:

    您的代码中有两个错误。

    1. 无法在 Lua 处理程序之间传递 cosocket 对象(强调由我添加):

      此 API 函数创建的 cosocket 对象与创建它的 Lua 处理程序具有完全相同的生命周期。 所以永远不要将 cosocket 对象传递给任何其他 Lua 处理程序(包括 ngx.timer 回调函数),并且永远不要在不同的 Nginx 请求之间共享 cosocket 对象。

      https://github.com/openresty/lua-nginx-module#ngxsockettcp

      在您的情况下,对 cosocket 对象的引用存储在 client 表 (client._sock) 中。

    2. ngx.print/ngx.sayngx.timer.* 上下文中不可用。

      https://github.com/openresty/lua-nginx-module#ngxsay(检查 context: 部分)。

      您可以改用ngx.log(它写入nginx日志,在nginx.conf中设置error_log stderr debug;以将日志打印到stderr)。

    以下代码按预期工作:

    ngx.timer.at(2, function()
      local client = redis:new()
      client:connect('127.0.0.1' ,6379)
      ngx.log(ngx.DEBUG, #client:keys('*'))
    end)
    

    【讨论】:

    猜你喜欢
    • 2010-10-28
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2021-07-19
    • 2021-03-27
    • 2021-05-08
    • 2021-12-06
    相关资源
    最近更新 更多