如何用redis實現分布式鎖,redis實現分布式鎖

來源:互聯網
上載者:User

如何用redis實現分布式鎖,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.



相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.