Distributed Interview Questions (1): Distributed Lock

Q:
Distributed lock
1. In a distributed system environment, a method can only be executed by one thread of one machine at the same time
2. Highly available lock acquisition and release lock
3. High performance lock acquisition and release lock
4. With reentrant features (can be understood as re-entry, concurrent use by more than one task without worrying about data errors)
5. With lock failure mechanism to prevent deadlock
6. With non-blocking lock feature, that is, the lock will not be acquired Return directly to the failure to acquire the lock

Q:
Distributed lock based on zookeeper
1. Some features of zookeeper

Ordered node: If the current parent node is /lock, we can create a child node under this parent node; zookeeper provides an optional ordered feature, for example, we can create a child node "/lock/node-" and Specify order, then zookeeper will automatically add an integer serial number according to the current number of child nodes when generating child nodes, that is to say, if it is the first child node created, then the generated child node is /lock/node-0000000000, next A node is /lock/node-0000000001, and so on.

Temporary node: The client can establish a temporary node. Zookeeper will automatically delete the node after the session ends or the session times out.

Event monitoring: When reading data, we can set event monitoring for the node at the same time. When the node data or structure changes, zookeeper will notify the client. Currently zookeeper has the following four events:
1. Node creation;
2. Node deletion;
3. Node data modification;
4. Child node change.

2. Implementation
①The client connects to zookeeper and creates temporary and orderly child nodes under /lock. The first client corresponds to the child node /lock/lock-1, and the second one is /lock/lock- 2, and so on.
②The client obtains the child node list under /lock, and judges whether the child node it created is the child node with the smallest sequence number in the current child node list. If it is, it is considered to be locked, otherwise it monitors the child node change message of /lock and obtains the child node. After the node change notification, repeat this step until the lock is obtained;
③Execute the business code;
④After completing the business process, delete the corresponding child node to release the lock.

Q:
Implementation of zookeeper distributed lock based on curator

public static void main(String[] args) throws Exception {
    
    
        //创建zookeeper的客户端
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

        CuratorFramework client = CuratorFrameworkFactory.newClient("10.21.41.181:2181,10.21.42.47:2181,10.21.49.252:2181", retryPolicy);

        client.start();

        //创建分布式锁, 锁空间的根节点路径为/curator/lock
        InterProcessMutex mutex = new InterProcessMutex(client, "/curator/lock");

        mutex.acquire();

        //获得了锁, 进行业务流程
        System.out.println("Enter mutex");

        //完成业务流程, 释放锁
        mutex.release();

        //关闭客户端
        client.close();

    }

Q: Redis-
based distributed lock
1. Process
1. In order to obtain the lock, Service A initiates the following command to Redis: SET productId:lock 0xx9p03001 NX PX 30000 Among them, "productId" is defined by itself and can be related to this business id, "0xx9p03001" is a string of random values, which must be globally unique (the reason will be mentioned later), "NX" refers to if and only if the key (that is, "productId:lock" in the case) is in Redis If it does not exist, the execution is successful, otherwise the execution fails. "PX 30000" means that after 30 seconds, the key will be automatically deleted. Success is returned after executing the command, indicating that the service successfully obtained the lock.
2. In order to obtain the lock, Service B initiates the same command to Redis: SET productId:lock 0000111 NX PX 30000 Since the key with the same name already exists in Redis and has not expired, the command execution fails and Service B fails to obtain the lock. Service B enters the cyclic request state, such as sending a request to Redis every 1 second (set by itself), until the execution is successful and the lock is obtained.
3. The execution time of service A's business code exceeds 30 seconds, which causes the key to time out, so Redis automatically deletes the key. At this time, service B sends the command again and executes successfully, assuming that the value set in this request is 0000222.
4. After the execution of service A is completed, in order to release the lock, service A will actively initiate a key deletion request to Redis.

2. Realize
① The locking
client integrates Redisson. Before locking, you first need to select a Redis Master in the cluster through the hash algorithm. The subsequent locking and unlocking processes are all tied to this Redis Master. Between the slave nodes. ②Execute the
lua script to realize the lock.
③Watch dog automatically extend the
watch dog is a background thread, it will observe whether the current client still holds the lock every 10 seconds, if it holds, the client may still be using the lock, so extend the lock Remaining survival time.
④Release the lock mechanism. If lock.unlock() is executed, Redis will find the test data structure above and reduce the number of locks by one. If the number of locks is found to be 0 after the reduction, it means that the current client no longer holds the lock, so execute the del test command to delete this key from Redis.

// 准备为名为"test"的key加锁
RLock lock = redisson.getLock("test");
// 加锁
lock.lock();
// 解锁
lock.unlock();

The official account of this blog: Muzi network side business, welcome to pay attention to the exchange!

Guess you like

Origin blog.csdn.net/ncw8080/article/details/113879257