亚欧色一区w666天堂,色情一区二区三区免费看,少妇特黄A片一区二区三区,亚洲人成网站999久久久综合,国产av熟女一区二区三区

  • 發布文章
  • 消息中心
點贊
收藏
評論
分享
原創

lua限時執行

2024-10-11 10:17:19
8
0

背景

openresty中使用lua提供業務的內容實現,有些客戶請求或者處理過程需要有時效性,比如去第三方服務器獲取數據,或者有其它io耗時的操作,而需要在限定時間內完成的場景。

實現方案

將需要執行的func和超時時間作為參數

  1. 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
  2. 雙協程
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
0條評論
0 / 1000
張****東
10文章數
0粉絲數
張****東
10 文章 | 0 粉絲
張****東
10文章數
0粉絲數
張****東
10 文章 | 0 粉絲
原創

lua限時執行

2024-10-11 10:17:19
8
0

背景

openresty中使用lua提供業務的內容實現,有些客戶請求或者處理過程需要有時效性,比如去第三方服務器獲取數據,或者有其它io耗時的操作,而需要在限定時間內完成的場景。

實現方案

將需要執行的func和超時時間作為參數

  1. 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
  2. 雙協程
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
文章來自個人專欄
文章 | 訂閱
0條評論
0 / 1000
請輸入你的評論
0
0