当前位置:网站首页>Distributed (III) -- realize distributed lock
Distributed (III) -- realize distributed lock
2022-04-22 16:58:00 【jc_ hook】
In stand-alone applications , When multithreading synchronous access to a shared variable , It can be used. JVM Of synchronized Lock or lock Lock handling .
But when in a distributed cluster system , Multithreading 、 Multiple processes are distributed on different machines , This will invalidate the concurrent control lock policy in the case of the original stand-alone deployment .

Therefore, a cross machine mutual exclusion mechanism is proposed to control the access of shared resources —— Distributed lock
Catalog
One 、 Conditions for distributed
- In a distributed system environment , A method can only be accessed by one thread on a machine at a time
- Highly available acquire and release locks
- Efficient lock acquisition and release
- Reentrant feature ( Re enter , Used concurrently by multiple tasks , No more than worrying about data errors )
- Failure mechanism with lock , Prevent deadlock
- Features of non blocking lock , The lock was not acquired , Direct return to get lock failed
Two 、 Three ways of implementation
Distributed systems should comply with CAP theory :
C(Consistency): Uniformity
A(Availability): Usability
P(Partition Tolerance): Partition tolerance
These three cannot be achieved at the same time , In most scenarios , All need sacrifice Strong consistency In exchange for the system High availability , Systems often only need to guarantee “ Final consistency ”.
The three ways to implement distributed locks are mainly :
- Implementation of distributed lock based on Database
- be based on redis Implement distributed locks
- be based on Zookeeper Implement distributed locks
Based on the fact that the author has not known Zookeeper, So it will not be based on Zookeeper Implement distributed locks , Wait until you learn later ~
3、 ... and 、 Implementation of distributed lock based on Database
Create a lock table , By manipulating the data of the table .
DROP TABLE IF EXISTS `methodLock`;
CREATE TABLE `methodLock` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT ' Primary key ',
`method_name` varchar(64) NOT NULL COMMENT ' Locked method name ',
`desc` varchar(255) NOT NULL COMMENT ' Notes ',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uidx_method_name` (`method_name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT=' Method in locking ';
Yes method_name Did Uniqueness constraint
When a method or resource needs to be locked , Insert record in lock table , If there are multiple requests submitted to the database at the same time , The database will guarantee that only one operation can succeed
INSERT INTO methodLock (method_name, desc) VALUES ('methodName', ' Locked method name or resource name ');
Delete records when releasing the lock
DELETE FROM methodLock WHERE method_name='methodName';
Using database to realize distributed lock is simple , But some problems still need to be solved :
- The availability and performance of distributed locks are directly affected by the availability and performance of databases ;
- No, Lock failure The mechanism of , The data is not deleted when the lock is released due to server downtime , In this way, the lock cannot be obtained after the server is restored . So you need to have field records Failure time , Delete invalid data through scheduled tasks ;
- Do not have Blocking lock characteristic , Fail to get lock and return directly , So we need to optimize the acquisition logic , Loop multiple times to get
- Do not have Reentrant Characteristics of , When a machine is locked , Unable to insert data successfully again . So you need to have field records machine and Threads Information , When acquiring the lock, it is related to the currently acquired machine and site information , If identical , Then get the lock directly .
Four 、 be based on Redis Implement distributed locks
redis It has very high performance
redis The command supports this better , It's easy to use .
4.1 Realization thought
- When getting the lock , adopt setnx Lock , The lock value Value is a randomly generated UUID, Judge when releasing the lock through this
- When getting the lock , use expire Command to add a timeout to the lock , After this time, the lock is abandoned
- When you release the lock , adopt UUID Decide whether to lock , If it's time to lock , execute delete Lock release
4.2 Use command
- setnx: The order is at the designated key When there is no , by key Set the specified value , Set up the success , return 1 . Setup failed , return 0
- expire: Set up key The expiration time of ,key No longer available after expiration . Unit in seconds
- delete: Delete key value
版权声明
本文为[jc_ hook]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221652504935.html
边栏推荐
- Performance evaluation of rust asynchronous framework
- 基于深度学习的日志数据异常检测
- Numpy Fundamentals (creation, index, common functions)
- 斗志斗勇之mysql
- What is the advantage of asemi low voltage drop Schottky diode over ordinary Schottky diode?
- [Dahua cloud native] wonderful relationship between message queue and express cabinet (with video)
- 7 capabilities of data analysis: sorting out data needs
- 【滤波与卷积(二)】
- LeetCode刷题计划——单调数列
- 中金证券开户app叫什么?股票开户怎么样佣金优惠又安全?
猜你喜欢

JD side: how can a child thread get the value of the parent thread ThreadLocal? I got...

SDN学习之Opendaylight浅析(一)

对数器的概念和使用

AQS源码阅读

"Addition and subtraction" of aftership technology upgrading under the long river of SaaS

2022最贵新股来了,小米、华为小赚10倍

Detailed chart of chatevents inspection record (x)

敬語 謙譲

MySQL_ 00_ Get to know MySQL

Cvpr2019 domain adaptation / semantic segmentation: adapting structural information across domains for boosting SEMA
随机推荐
web安全工具Burp_suite安装及使用教程(专业版)
【ES6】扩展运算符、symbol、迭代器
运维自动化之ansible--(playbook模式)
Merge two ordered linked lists (delete the same content)
最新流程引擎 flowable 6.7.2 更新说明
基于深度模型的日志序列异常检测
wps excel 怎么复制工作表?(移动或复制工作表)
frp反向代理
[corner detection]
What are the functional problems of UI testing- Ze zhongyun test
Your password does not satisfy the current policy requirements
蕉下在走完美日记的老路
IDEA代码重构小技巧(VIP典藏版)
ifconfig、route、ip route、ip addr、 ip link 用法
[Unity] 使用 Animation Rigging 制作瞄准 IK 1
数据分析7大能力:梳理数据需求
Explain JVM memory model in detail
NFT platform security guide
[filtering and convolution (II)]
bisect——对列表插入新数据仍然保持有序