首页 / REDIS / 如何用redis实现分布式锁
如何用redis实现分布式锁
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何用redis实现分布式锁,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1770字,纯文字阅读大概需要3分钟。
内容图文
![如何用redis实现分布式锁](/upload/InfoBanner/zyjiaocheng/561/fe7850f4254c49a5a7ca012680106d5c.jpg)
引子 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 ti
引子
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实现分布式锁所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。