如何用redis实现分布式锁
来源:互联网 发布:nat123 80端口 免费 编辑:程序博客网 时间:2024/04/30 01:42
引子
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.
- 如何用redis实现分布式锁
- 如何用REDIS实现分布式缓存
- 如何用REDIS实现分布式缓存
- 如何用 redis 造一把分布式锁
- 如何用Redlock实现分布式锁
- 如何用Redlock实现分布式锁
- 关于如何用Zookeeper实现分布式锁机制
- 如何用Redis
- Redis实现分布式锁
- Redis 分布式锁实现
- Redis 分布式锁实现
- Redis实现分布式锁
- redis实现分布式锁
- Redis实现分布式锁
- 分布式锁redis实现
- Redis 分布式锁实现
- redis分布式锁实现
- redis实现分布式锁
- FZU Problem 2102 Solve equation 第三届福建省大学生程序设计竞赛
- linux脚本实现自动输入密码
- 用 SpriteKit 做一个逃逸游戏 (5)
- Codeforces Round #277 (Div. 2)
- 满足条件的整数
- 如何用redis实现分布式锁
- Linux/Unix IO多路复用之select网络编程(含源码)
- Dedecms自定义sql 出现错误Safe Alert: Request Error step 2!
- 谷歌公司发布程序员养成指南,推荐相关在线课程
- 已知有个rand7()的函数,返回1到7随机自然数,让利用这个rand7()构造rand10() 随机1~10
- 有序表的实现
- Linux/Unix IO多路复用之poll网络编程(含源码)
- call by name 与 call by value in scala
- 最大商