当前位置:网站首页>Three implementation methods of distributed lock

Three implementation methods of distributed lock

2022-06-23 09:40:00 Linging_ twenty-four

github:https://github.com/Linging24/lock.git

Requirements for distributed lock implementation :
1、 In a distributed environment , Only one client can hold the lock at any time
2、 A deadlock will not occur
3、 Lock your own client , It can only be unlocked by itself

1、 Data based implementation

  • Create database lock table :
CREATE TABLE `lock_record` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT ' Primary key ',
  `lock_name` varchar(50) DEFAULT NULL COMMENT ' Lock name ',
  PRIMARY KEY (`id`),
  UNIQUE KEY `lock_name` (`lock_name`)
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8;

Ideas : When a thread enters shared code , Insert a record into the database , When threads of other distributed nodes want to access the shared code , You will first query whether such a lock record exists in the database , If it exists, wait for the lock , Otherwise, get the lock , Execute shared code .

2、 be based on redis Realization

  • Use setnx Instructions , But there is if after locking , If the program throws an exception , It will cause the lock to never be released , It is possible to set a timeout , If the time comes, the lock will be released , However, it is necessary to ensure that the locking operation and setting the timeout time are atomic operations .
  • because redis Generally, it is deployed in a cluster , The first method is only applicable to the single node method , For cluster locking, use redission.

Be careful : Why does the first method only apply to a single node redis, If it is applied to the cluster, what problems will it cause ?
Under Cluster , All write operations are on the primary node , So the locks are all on the primary node , If the master node hangs up , Then the slave node will preempt the lock , At this time, if the primary node has not been down yet , Some clients have acquired locks , And operate resources , And from The client that obtains the lock from the node is also operating on the resource , It is possible that multiple clients are operating unified resources , In this way, resources cannot be locked .

Seven ways to implement :
https://www.cnblogs.com/wangyingshuo/p/14510524.html

3、 be based on zookpeer Realization
 Insert picture description here

原网站

版权声明
本文为[Linging_ twenty-four]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230929350033.html