当前位置:网站首页>Implementation of distributed lock
Implementation of distributed lock
2022-07-26 03:59:00 【I an】
1. What is distributed lock
In order to ensure the consistency of data in the concurrent environment , We usually use locking . If the data only exists on one server , The problem of inconsistent data can be solved by using a single lock .
In distributed clusters , The value of a variable may be shared by multiple nodes of a cluster , At this time, to ensure the consistency of variables , It is not enough to lock only one machine , What we need to do is lock the cluster , This is the distributed lock .
2. Conditions for implementing distributed locks
- In the distributed system environment , The critical area that is locked can only be executed by one thread of a node at the same time
- Acquiring and releasing locks require high availability
- Reentrancy needs to be guaranteed
- Lock failure mechanism , Prevent deadlock
- Non blocking features are required , If the lock is not obtained within a certain period of time, it will directly return to the failure of obtaining the lock
3. Three ways to realize distributed lock
3.1 be based on Redis Implement distributed locks
- When getting the lock , Use setnx Lock , That is to say redis A lock record is stored in , And use expire Command to add a timeout to the lock , After that time, the lock will be released automatically , The lock value Value is a randomly generated UUID, Judge when releasing the lock through this .
- When acquiring the lock, a timeout for acquiring is also set , If it exceeds this time, give up acquiring lock .
- When you release the lock , adopt UUID Decide whether to lock , If it's time to lock , execute delete Lock release .
3.2 Implementation of distributed lock based on Database
If not used Redis And a series of caching middleware , You can also use databases to implement distributed locks , Store the lock record in the database .
This is not recommended , Because you need to implement the timeout logic by yourself , The throughput of accessing the database at the same time is not as good as that of caching , It is difficult to ensure high availability in an environment of high concurrency and competitive locks .
3.3 be based on zookeeper Implement distributed locks
- Create a directory mylock;
- Threads A To get the lock is in mylock Create temporary order node under directory ;
- obtain mylock All child nodes in the directory , Then get the smaller brother node , If it doesn't exist , It means that the front line The sequence number of Chengshun is the smallest , Gets the lock ;
- Threads B Get all nodes , Judge that you are not the smallest node , Set a node smaller than yourself to listen to ;
- Threads A processed , Delete your own node , Threads B A change event was detected , Judge whether you are the smallest node , If so, get the lock .
4. be based on Redis Code example of implementing distributed lock
/** * Lock operation */
private void lock() {
String id = UUID.randomUUID().toString();
// randomId:ThreadLocal Variable , Storage thread UUID, With global uniqueness
randomId.set(id);
try {
// Lock taking timeout :65 * 500 ms
tryLock(id, 65);
} catch (Exception e) {
log.error("lock fail", e);
}
}
private void tryLock(String val, int repeatTimes) throws Exception {
// redis client
CacheProvider cacheProvider = CRedisClient.getCacheProvider();
// locked:ThreadLocal Variable , Record whether the current thread has a lock , Ensure reentry
if (!Objects.isNull(locked.get())) {
return;
}
// Lock record timeout :30 s
if (!cacheProvider.set(LOCK, val, "NX", "EX", 30)) {
if (repeatTimes > 0) {
Thread.sleep(500);
tryLock(val, repeatTimes - 1);
} else {
// Check for abnormalities
long ttl = cacheProvider.ttl(LOCK);
if (ttl > 30 || ttl == -1) {
cacheProvider.del(LOCK);
}
throw new TimeoutException("try lock time out");
}
} else{
locked.set(true);
}
}
/** * Unlock operation */
private void unlock() {
CacheProvider cacheProvider = CRedisClient.getCacheProvider();
String expected = randomId.get();
String actual = cacheProvider.get(LOCK);
// confirm unlock Identity of the thread
if (Objects.equals(expected, actual)) {
cacheProvider.del(LOCK);
}
locked.remove();
}
边栏推荐
- Tactile intelligent sharing-rk3568 application in scenic spot navigation robot
- [Reading Notes - > data analysis] Introduction to BDA textbook data analysis
- PHP object conversion array
- 座椅/安全配置升级 新款沃尔沃S90行政体验到位了吗
- JS Base64 encoding and decoding
- Dat of deep learning
- 用GaussDB(for Redis)存画像,推荐业务轻松降本60%
- JS upload avatar (you can understand it after reading it, trust me)
- redux
- WAF details
猜你喜欢

redux

资深报表开发经验总结:明白这一点,没有做不好的报表

leetcode: 102. 二叉树的层序遍历

【程序员必备】七夕表白攻略:”月遇从云,花遇和风,晚上的夜空很美“。(附源码合集)

Wechat applet to realize music player (4) (use pubsubjs to realize inter page communication)

Portable power fast charging scheme 30W automatic pressure rise and fall PD fast charging

1311_硬件设计_ICT概念、应用以及优缺点学习小结

Moco V2: further upgrade of Moco series

基于Caffe ResNet-50网络实现图片分类(仅推理)的实验复现

第十八章:2位a~b进制中均位奇观探索,指定整数的 3x+1 转化过程,指定区间验证角谷猜想,探求4份黑洞数,验证3位黑洞数
随机推荐
PHP <=> 太空船运算符(组合比较符)
Portable power fast charging scheme 30W automatic pressure rise and fall PD fast charging
PHP object conversion array
In PHP, you can use the abs() function to turn negative numbers into positive numbers
基于JSP实现网上商城系统
What is the problem of the time series database that has been developed for 5 years?
Opencv learning notes - remapping
Div setting height does not take effect
E-commerce operator Xiaobai, how to get started quickly and learn data analysis?
operator new、operator delete补充讲义
Chapter 18: explore the wonders of the mean in the 2-bit a~b system, specify the 3x+1 conversion process of integers, specify an interval to verify the angular Valley conjecture, explore the number of
[MCU simulation project] external interrupt 0 and 1 control two digit nixie tube to count
Let Baidu collect, crawler own website
基于移位寄存器的同步FIFO
day03_ 1_ Idea tutorial
中国数据库 OceanBase 入选 Forrester Translytical 数据平台报告
Dtcloud the next day
[Reading Notes - > data analysis] Introduction to BDA textbook data analysis
File upload error: current request is not a multipart request
leetcode: 102. 二叉树的层序遍历