Distributed locks are stored in a shared storage system and can be accessed and obtained by multiple clients

Redis happens to be a shared storage system

The connection between distributed locking and stand-alone locking

For a lock that runs on a single machine, it is actually a variable.

Distributed locks require this variable to be in the shared storage system, therefore

  • Distributed locking Requires atomicity of operations during lock and release.
  • The shared storage system stores lock variables, so when the shared storage system fails, it is troublesome. Therefore, the reliability of the system must be ensured

Implementing distributed locking

Distributed locking based on a single Redis node

Redis uses key-value pairs to hold lock variables

Lock needs :1, read the lock, 2, determine whether the variable is 0,3, set the lock variable to 1

How do you guarantee atomicity

Redis guarantees atomicity in two general ways:

  • Use Redis single command operations and Lua scripts

  • SETNX: Sets the value of the key-value pair if name does not exist, otherwise no operation

  • DEL deletes the lock (even if the variable is deleted, SETNX will set it up next time)

Therefore, you can use the above two commands to lock and release the lock

risk

If abnormal exit after locking will make others unable to lock, it is recommended to add an expiration time

After A is locked, if B releases the lock, A will be released by mistake. At this time, C will be locked by two people at the same time. Therefore, different clients need to be differentiated and different lock values can be set for different clients.

Lua scripts are required to ensure atomicity

Distributed lock based on multiple Redis nodes

Multiple Redis nodes guarantee high reliability even if a broken node works

Redlock: the client and multiple independent Redis instances request the lock in turn. If the client can successfully complete the lock operation with more than half of the instances, the lock is successful. Otherwise, the client can successfully complete the lock operation

  1. The client obtains the current time
  2. The client locks N Redis instances in sequence
    • Single-node lock + Set timeout period of lock operation (tens of milliseconds) : If the lock is not successfully added before the timeout, the system skips it
  3. Calculate the total time of locking

Determination of success of locking

  • More than half got locks
  • The total time for the client to obtain a lock does not exceed the lock validity period

The lock validity period is the initial validity period of the lock – total time

Please add the following text and link at the end of the article: This article is participating in the “Gold Digging Booklet free learning!” Event, click to view details of the event