当前位置:网站首页>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();
}
边栏推荐
- Bracket nesting problem (recommended Collection)
- Lua and go mixed call debugging records support cross platform (implemented through C and luajit)
- 5 years, 1.4W times, NFT og's road to immortality Web3 column
- Graduation season & harvest season, leave your beautiful moments
- Multi merchant mall system function disassembly lecture 15 - platform side member label
- 中国数据库 OceanBase 入选 Forrester Translytical 数据平台报告
- Uncaught TypeError: $(...). Onmousenter is not a function JS error, solution:
- 座椅/安全配置升级 新款沃尔沃S90行政体验到位了吗
- Laravel8 implements interface authentication encapsulation using JWT
- 软考 系统架构设计师 简明教程 | 案例分析解题技巧
猜你喜欢

Lua and go mixed call debugging records support cross platform (implemented through C and luajit)

MySQL index failure scenarios and Solutions

Aike AI frontier promotion (7.18)

cpu和gpu已过时,npu和apu的时代开始

KBPC1510-ASEMI大芯片15A整流桥KBPC1510

General test case writing specification

Matlab paper illustration drawing template issue 39 - stairs

Visio: how do Gantt charts merge cells? Solution: overwrite cells

ZK snark: about private key, ring signature, zkksp

(翻译)按钮位置约定能强化用户使用习惯
随机推荐
Zkevm: summary of zkevm and L1 by Mina's CEO
The second article, which is still unfinished, will be introduced again, and continue to explain oracledb_ Exporter monitors Oracle, a very low intrusive monitoring scheme.
[cloud native kubernetes] how to use configmap under kubernetes cluster
Realization of online shopping mall system based on JSP
php 保存数组到文件 var_export、serialize
加班一周开发了报表系统,这个低代码免费IT报表神器太好用了
座椅/安全配置升级 新款沃尔沃S90行政体验到位了吗
按键消抖的Verilog实现
2.9.4 Ext JS的布尔对象类型处理及便捷方法
[Reading Notes - > data analysis] Introduction to BDA textbook data analysis
[cloud native] talk about the understanding of the old message middleware ActiveMQ
Graduation season & harvest season, leave your beautiful moments
微信小程序实现音乐播放器(4)(使用pubsubjs实现页面间通信)
What is the problem of the time series database that has been developed for 5 years?
MySQL index failure scenarios and Solutions
cpu和gpu已过时,npu和apu的时代开始
Opencv learning notes -- Hough transform
Introduction to UFS CLK gate
苹果在其产品中拿掉了最后一颗Intel芯片
oracle 11g “密码延迟验证”特性