redis-分布式锁

redis提供了一个分布式锁的教科书式(canonical)的实现: Redlock, 实现了一个DLM(Distributed Lock Manager).

为了能够非常有效的使用分布式锁,需要至少三个条件:

1.安全保证:互斥。在任何时间, 只有一个client 获取到一个锁。

2.存活A:死亡即释放。

3.存活B:容错,只要 主redis 节点恢复, 客户端就能够获取和释放锁

其他实现的不足:

实现A:

    通过在redis中设置一个key,并设置key的存活时间,当客户端不需要时,delete这个key 就表示释放了资源。该模型有问题,分析如下:

  1. Client A acquires the lock in the master.
  2. The master crashes before the write to the key is transmitted to the slave.
  3. The slave gets promoted to master.
  4. Client B acquires the lock to the same resource A already holds a lock for. SAFETY VIOLATION!

 

RedLock的实现:

 SET resource_name my_random_value NX PX 30000

The command will set the key only if it does not already exist (NX option), with an expire of 30000 milliseconds (PX option). 

删除这个key时,需要比较myrandomvalue,如果是该客户端的值, 那么就给删除

if redis.call("get",KEYS[1]) == ARGV[1] then
    return redis.call("del",KEYS[1])
else
    return 0
end

保证了谁设置的谁清除, 其他人清楚不了。 所以逻辑很简单。

 

未完 待续

 

你可能感兴趣的:(高并发后台服务中间件,redis,分布式)