The initial Redis Distributed Lock

Concurrent problems often distributed application, such as the status of the user to make a modification, then the extracted data is then directed to the first modification, but this will often cause problems, because the two read and write operations are not atomic (integral) operation. When the operation at the same time often lead to concurrency issues.
 
Then you should use distributed lock.
 
Distributed Lock in Reids is actually accounted for the equivalent of a pit, when someone on the outside and then have to wait for others to pit, while accounting for only one person pit. Setnx provide an instruction to the lock of the Redis key:
setnx mylock true
... do something ... // do some business logic
del mylock // release the lock
 
This seems the bin down. No, it's a problem. If I was doing some business logic of a problem when unreachable del command to release the lock when it not to enter an infinite loop, the lock is not released, others not lock.
This is embarrassing, but we do not have a command expiration time settings? For ah that expire command:
setnx mylock true
expire mylock 5 // set the expiration time of 5s
... do something ... // do some business logic
del mylock // release the lock
 
This is not to solve the problem? Do not get too excited, in case a problem between me and expire setnx it, it is still the same, ah, the problem remains the same, there was still deadlock. Can we use that matters to solve it? The answer is not enough, because the transaction is not executed either perform or else, and we need that if / else operations, expire instruction is dependent on the instruction setnx result, if setnx did not grab the lock, then expire is do not perform.
Now we have to analyze why there is such a problem, in fact, because setnx expire and are not two atomic operations, so this is bound to have problems. Can we merge these two instructions about it? The answer is yes. Redis provides a set of instructions for us:
set mylock true expire 5 nx // expire and the binding setnx
... do something ... // do some business logic
del mylock // release the lock
This set of instructions is where esoteric distributed lock.
 
但是上面的操作还是存在问题的,因为设置了过期时间。万一我的业务逻辑执行时长超过过期时间的化,那么我就释放掉了锁,我都没执行完呢就没了,难受啊。这就是超时问题。所以分布式锁还是不要用来去执行时间比较长的任务。

Guess you like

Origin www.cnblogs.com/lgxblog/p/11102072.html