如何用redis实现分布式锁
2014-11-12 15:26
1201 查看
引子
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命令页介绍了新的方案:SETcommand + 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.
相关文章推荐
- 如何操作Redis和zookeeper实现分布式锁
- Redis实现分布式锁(setnx、getset、incr)以及如何处理超时情况(一)
- Redis 分布式锁实现
- 使用 Redis 实现分布式锁(转)
- zookeeper如何实现分布式锁(羊群效应)
- Redis 分布式锁实现
- 详解Java如何实现基于Redis的分布式锁
- 用Redis实现分布式锁
- 如何用 redis 造一把分布式锁
- 分布式缓存技术redis学习系列(五)——redis实战(redis与spring整合,分布式锁实现)
- Java实现基于Redis的分布式锁
- StackExchange Redis如何实现BRPOP/BLPOP
- shiro安全框架扩展教程--如何扩展实现集中式session管理(redis,memcached等)
- [转载] Redis实现分布式锁
- 分布式缓存技术redis学习系列(五)——redis实战(redis与spring整合,分布式锁实现)
- 在 Redis 上实现的分布式锁
- shiro安全框架扩展教程--如何扩展实现我们的缓存机制(第三方容器redis,memcached)
- 分布式锁实现(基于redis)
- REDIS 学习(10)流程图解使用redis实现分布式锁