Redis distributed lock

1. Setnx and expire are not atomic. Maybe after setNx, the service hangs, so the object is locked forever. So you have to set a timeout. Use lua scripts to combine Senx and EXPIRE. 2. After redis2.16 provide new set parameter set key value nx px 3000, command. 3. In distributed locks, you need to release the lock after a task is complete or an exception occurs.

  • There is such A situation A: request A shackles, shackles time 3s. When the service processing time exceeds 3s, the lock is automatically released. So request B can also get the lock. At this point, lock A ends and lock B is released. B releases the lock after processing the service logic and finds that the lock does not exist.
  • Alternatively, case B: Request A releases the lock on request B. Request C comes in, and B releases c’s lock. For the above solution, extend the lock time, evaluate the business processing time plus buffer. The downside is that when an exception occurs, such as a lock, the application service is restarted, and the lock takes some time to release automatically. Setting the time too short doesn’t work either. A while rotation can be set, and when the time exceeds two thirds of the estimated setting time, the value is reassigned.

4. To avoid the extreme case of releasing someone else’s lock, check value. Value Specifies the service meaning, such as the UUID. Delete key and check whether value is its own value. Check the value of the key before deleting it. Lua scripts are also used here to maintain atomicity.

The redisson framework is widely used in the industry. The underlying redlock encapsulates common operations. Have time to take a look at this source, forget. Will the interview feel like asking? Ahhhhh. Update this article sometime

Zk lock

The second way to realize distributed lock is to use the temporary node of ZooKeeper to realize the lock first come first served to ensure the order. Start by creating a root node permanent node such as order. Each child node is then created under the parent node. Child nodes are added in the sequence in which they are created. The node with the smallest serial number is locked every time. The latter listens on the former and notifies the latter when the current node completes its operation. Then the latter node will determine whether it is the node with the smallest serial number, if the logic is not executed, it will continue to wait. The reason for setting up a temporary node is that it will be removed once the server node is actually deleted or disconnected from the server. The next node in line also receives the deletion event. Avoid all nodes listening when one node exits. Only after listening directly in front.