Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

A distributed lock

The definition of distributed locks

Distributed locking is a way to control the simultaneous access of distributed applications to shared resources.

What characteristics should a distributed lock have

  • Mutual exclusivity

Only one client holds the lock at any time.

  • Die lock

Distributed lock is essentially A rented lock. If client A encounters an exception (such as an outage) after obtaining the lock, the lock can be automatically released after A period of time. Resources are not locked and other clients are allowed to obtain the lock.

  • consistency

When the business has a high requirement for mutual exclusion. In the cluster, the lock on the server (such as Redis) needs to be maintained after the master breaks down and the replica becomes the Master. After the lock is switched to the new master, the lock remains in the original state.

A more common implementation of distributed locks

  • zookeeper
  • Database based implementation
  • Redis

Today we will talk about distributed locking based on Redis implementation

Redis implements distributed locking

implementation

  • Lock command: SET key value NX EX 5(unit: second). If the key does not exist, the system sets the key and returns success. If the key does not exist, the system returns failure.
  • Unlock command: Check whether the lock is held by the current thread.
if redis.call("get", KEYS[1]) == ARGV[1] then 

    return redis.call("del", KEYS[1]) 

else 

    return 0 

end 
Copy the code
  • The set command adds an expire timeout to automatically release lock deadlocks. In this way, there is a problem. When the task is not finished, it reaches the timeout period and the lock is automatically released. At this time, it is necessary to renew the lock timeout period.
if redis.call("get",KEYS[1]) == ARGV[1] then 

    return redis.call("expire",KEYS[1], ARGV[2]) 
    
else 

    return 0 

end 
Copy the code

The following is how to unlock a client with a lock

The client example is out there, isn’t that nice

consistency

  • Standalone version: Redis is not locked, basically incurable;

  • The cluster version:

    • Cluster availability can be improved
    • Red locks are officially recommended
    • Use wait command

conclusion

Today we briefly talked about the redis based distributed lock implementation method, will be based on Java pseudo-code update to this article.