如何用redis實現分佈式鎖

引子

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 time expired: GETSET lock.foo <current Unix timestamp + lock timeout + 1>


不過這個方案有漏洞,就是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.


2.實現方案2

官方在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.


該方案有2個優化:

(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:

  • Instead of setting a fixed string, set a non-guessable large random string, called token.
  • Instead of releasing the lock with DEL, send a script that only removes the key if the value matches.



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