当前位置:网站首页>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();
}
边栏推荐
- 在 Istio 服务网格内连接外部 MySQL 数据库
- Matlab paper illustration drawing template issue 39 - stairs
- Three ways of redis cluster
- php 实现从1累加到100的算法
- In PHP, you can use the abs() function to turn negative numbers into positive numbers
- If you want to do a good job in software testing, you can first understand ast, SCA and penetration testing
- Dracoo master
- PHP method to find the location of session storage file
- Zkevm: summary of zkevm and L1 by Mina's CEO
- 1311_硬件设计_ICT概念、应用以及优缺点学习小结
猜你喜欢

Why are more and more users of Bing search?

php 查找 session 存储文件位置的方法

CPU and GPU are out of date, and the era of NPU and APU begins

《opencv学习笔记》-- 霍夫变换

How to use graffiti magic color product development kit

1311_ Hardware design_ Summary of ICT concept, application, advantages and disadvantages

Course selection information management system based on SSM

One stop monitoring of the software and hardware infrastructure of the whole university, and Suzhou University replaces PostgreSQL with time series database

File upload error: current request is not a multipart request

KBPC1510-ASEMI大芯片15A整流桥KBPC1510
随机推荐
[Reading Notes - > data analysis] Introduction to BDA textbook data analysis
STM32 state machine programming example - full automatic washing machine (Part 2)
微信小程序实现音乐播放器(5)
PHP implements the algorithm of adding from 1 to 100
【程序员必备】七夕表白攻略:”月遇从云,花遇和风,晚上的夜空很美“。(附源码合集)
php 查找 session 存储文件位置的方法
微信小程序实现音乐播放器(4)(使用pubsubjs实现页面间通信)
Asemi rectifier bridge gbu1510 parameters, gbu1510 specifications, gbu1510 package
oracle 11g “密码延迟验证”特性
括号嵌套问题(建议收藏)
Failed to install the hcmon driver
第十八章:2位a~b进制中均位奇观探索,指定整数的 3x+1 转化过程,指定区间验证角谷猜想,探求4份黑洞数,验证3位黑洞数
JS upload avatar (you can understand it after reading it, trust me)
测试工作不受重视?学长:你应该换位思考
【云原生】谈谈老牌消息中间件ActiveMQ的理解
Pits encountered by sdl2 OpenGL
[cloud native kubernetes] how to use configmap under kubernetes cluster
The B2B2C multi merchant system has rich functions and is very easy to open
PHP save array to var file_ export、serialize
【单片机仿真项目】外部中断0和1控制两位数码管进行计数