redis作为一个强大的key/value数据库,其实还可以用来实现轻量级的分布式锁。
最早官方在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.
官方在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:
原文地址:http://blog.csdn.net/patrickyoung6625/article/details/41041817