lua實現分佈式鎖

背景

基於openresty的後臺項目,需要實現一個分佈式鎖,但是不想用redis,增加組件依賴這種比較重的操作,於是想有沒有基於共享內存ngx.shared的分佈式鎖。 找到相關資料,發現openresty的shared api都是原子操作,也即是說get和set都是原子的,那麼只需要找到一種方法能夠確保get and set一起原子就可以了。於是搜到了下面的實現方法,通過add來實現,因爲add方法如果存在則失敗,成功說明沒有執行過set。

實現

local key = "updating"

-- the exptime, 60 sec, is to prevent dead-locking
local ok, err = mystore:add(key, 1, 60)
if not ok then
    if err == "exists" then
        -- some other nginx worker is already updating it, so we give up
    else
        -- some other error happens, handle it here
    end
else
    -- go update the data in mystore, you'd better use pcall here to prevent crashing in the middle
    mystore:delete(key)
end


參考

1. https://ms2008.github.io/2016/09/01/lua-atomicity-lock/

2. https://blog.csdn.net/qq_37322178/article/details/109072669

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章