zoukankan      html  css  js  c++  java
  • 怎样用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.



  • 相关阅读:
    ecplise自动提示失效,使用补全自动提示快捷键(Alt+/),但只显示“No Default Proposals”
    maven构建ssh工程
    pom.xml中坐标的组成
    依赖传递的规则
    maven中导入包版本冲突的解决
    maven工程的拆分与聚合
    maven的生命周期
    maven的常用命令
    在pom.xml中引入jar包坐标的依赖范围
    【stl的神奇操作】用集合搞定区间相交
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/6950221.html
Copyright © 2011-2022 走看看