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

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