Redis distributed lock the correct implementation

Reliability
First, you want to ensure that the distributed lock can be used, the following four conditions must be met:

  1. Mutually exclusive. At any time, only one client can hold the lock.
  2. A deadlock does not occur. Even with a client during a crash without holding the lock to unlock the initiative, but also to ensure follow-up to other clients can lock.
  3. Fault tolerant. As long as most of the Redis functioning node, the client can lock and unlock.
  4. The trouble should end it. Locking and unlocking must be the same client, the client's own people can not be added to the solution of the lock.

Lock, unlock code

public void sync(String lockKey) {
    boolean check = false;
    try {
        check = redisTemplate.opsForValue().setIfAbsent(lockKey, true);
        if(check){
            log.info("处理业务……");
        }
    } catch (Exception exception) {
        log.error(ToolsUtil.getStackMessage(exception));
    } finally {
        if(check){
            redisTemplate.delete(lockKey);
        }
    }
}

The first step, setting a variable check, mark padlock.
The second step, we try to lock operation with lockKey as the Key Redis, because Key is unique, it returns true if the lock is successful, if it returns false represents the lock failure.
The third step, check to determine whether the variable is true, if it is locked is true of our own behalf lockKey and locked business operations.
The fourth step, check to determine whether the variable is true, if it is locked is true of our own behalf lockKey and locked, then unlock.

Published 28 original articles · won praise 0 · views 10000 +

Guess you like

Origin blog.csdn.net/kaition/article/details/103990737