redis死锁处理

当Redis中出现死锁时,不能直接删除键并尝试SETNX,因为存在竞态条件。正确处理包括:SETNX失败后检查锁是否过期,若过期使用GETSET进行原子操作。如果GETSET返回的值已过期,则获取锁,否则说明其他客户端已获取锁,需重试。持有锁的客户端解锁前应先确认超时未过期,以应对复杂客户端故障。
摘要由CSDN通过智能技术生成

参见:https://redis.io/commands/setnx#handling-deadlocks
Handling deadlocks

When this happens we can’t just call DEL against the key to remove the lock and then try to issue a SETNX, as there is a race condition here, when multiple clients detected an expired lock and are trying to release it.

错误示例:
C1 and C2 read lock.foo to check the timestamp, because they both received 0 after executing SETNX, as the lock is still held by C3 that crashed after holding the lock.
C1 sends DEL lock.foo
C1 sends SETNX lock.foo and it succeeds
C2 sends DEL lock.foo
C2 sends SETNX lock.foo and it succeeds
ERROR: both C1 and C2 acquired the lock because of the race condition.

正确做法:
1、setnx失败
2、get检查锁是否过期
3、未过期睡眠一段时间重复前述步骤
4、已过期使用GETSET (原子操作,返回旧值,可检查key是否已被其他客户端重新设置过期时间)
5、若GETSET值已过期则获得锁
6、若GETSET值未过期,说明其他客户端更快地获得了锁,需重复上述步骤。重

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值