引子 redis作為一個(gè)強(qiáng)大的key/value數(shù)據(jù)庫(kù),其實(shí)還可以用來實(shí)現(xiàn)輕量級(jí)的分布式鎖。 1.實(shí)現(xiàn)方案1 最早官方在SETNX命令頁給了一個(gè)實(shí)現(xiàn): acquire lock: SETNX lock.foo current Unix time + lock timeout + 1 release lock: DEL lock.foo acquire lock when ti
redis作為一個(gè)強(qiáng)大的key/value數(shù)據(jù)庫(kù),其實(shí)還可以用來實(shí)現(xiàn)輕量級(jí)的分布式鎖。
最早官方在SETNX命令頁給了一個(gè)實(shí)現(xiàn):
acquire lock: SETNX lock.foo
release lock: DEL lock.foo
acquire lock when time expired: GETSET lock.foo
不過這個(gè)方案有漏洞,就是release lock用的DEL命令不支持cas刪除(delete if current value equals old value),這樣忽略race condition將會(huì)出現(xiàn)問題:
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 命令可以設(shè)置key過期時(shí)間:SET key value [EX seconds] [PX milliseconds] [NX|XX]
The lock will be auto-released after the expire time is reached.
(2)使用Lua腳本實(shí)現(xiàn)cas刪除(詳見SET命令頁)
It is possible to make this system more robust modifying the unlock schema as follows:
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com