背景
openresty中使用lua提供業務的內容實現,有些客戶請求或者處理過程需要有時效性,比如去第三方服務器獲取數據,或者有其它io耗時的操作,而需要在限定時間內完成的場景。
實現方案
將需要執行的func和超時時間作為參數
-
semaphore
local semaphore = require "ngx.semaphore" function _M.run(func, timeout) local sema = semaphore.new(0) local process = function() sema:post() end ngx.thread.spawn(func, process) return sema:wait(timeout) end - 雙協程
function _M.run(func, timeout)
local task_th = ngx.thread.spawn(func)
local timeout_th = ngx.thread.spawn(function(timeout)
ngx.sleep(timeout)
error("timeout")
end, timeout)
local ok, res = ngx.thread.wait(task_th, timeout_th)
if not ok then
if res == "timeout" then
ngx.thread.kill(task_th)
return false, "timeout"
else
return false, res
end
end
ngx.thread.kill(timeout_th)
return true
end