引子 redis作為一個強大的key/value數據庫,其實還可以用來實現輕量級的分布式鎖。 1.實現方案1 最早官方在SETNX命令頁給了一個實現: acquire lock: SETNX lock.foo current Unix time + lock timeout + 1 release lock: DEL lock.foo acquire lock when ti
redis作為一個強大的key/value數據庫,其實還可以用來實現輕量級的分布式鎖。
最早官方在SETNX命令頁給了一個實現:
acquire lock: SETNX lock.foo
release lock: DEL lock.foo
acquire lock when time expired: GETSET lock.foo
不過這個方案有漏洞,就是release lock用的DEL命令不支持cas刪除(delete if current value equals old value),這樣忽略race condition將會出現問題:
A client will try to release the lock after the expire time deleting the key created by another client that acquired the lock later.
官方在SETNX命令頁介紹了新的方案:SET command + Lua script:
Starting with Redis 2.6.12 it is possible to create a much simpler locking primitive using the SET command to acquire the lock, and a simple Lua script to release the lock. The pattern is documented in the SET command page.
The old SETNX based pattern is documented below for historical reasons.
(1)SET 命令可以設置key過期時間:SET key value [EX seconds] [PX milliseconds] [NX|XX]
The lock will be auto-released after the expire time is reached.
(2)使用Lua腳本實現cas刪除(詳見SET命令頁)
It is possible to make this system more robust modifying the unlock schema as follows:
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com