当某些情况发生时,我们需要从 nginx 将事件记录到我们的事件服务器。我知道我可以使用 access_by_lua 进行 http 调用。由于事件记录可能会失败或需要更长的时间,我们不希望请求处理等待 http 操作完成。
如果我使用 lua 访问,则记录所需的时间将被添加到请求时间中。
有没有办法在异步过程中启动事件记录过程,以便请求可以继续,而事件记录可以花时间。
最佳答案
您可以在 content_by_lua_* 中进行通常的处理,并通过 ngx.eof()
明确指定响应输出流的结尾
因此 HTTP 请求将被毫不延迟地处理。
之后你可以做任何你想做的事情,例如使用 cosocket API 或 ngx.location.capture()
https://github.com/openresty/lua-nginx-module#ngxeof
这是文档中的示例:
location = /async {
keepalive_timeout 0;
content_by_lua_block {
ngx.say("got the task!")
ngx.eof() -- well written HTTP clients will close the connection at this point
-- access MySQL, PostgreSQL, Redis, Memcached, and etc here...
}
}
关于nginx lua 在不阻塞请求的情况下进行外部 http 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43337854/