当前位置:网站首页>Have you got all the distributed locks we used in those years
Have you got all the distributed locks we used in those years
2022-07-18 06:33:00 【Cheng Ming, Cheng Ming, you're going to be famous】
Features of distributed locks
- Mutual exclusivity : Like our local locks, mutex is the most basic , But distributed locks need to guarantee the mutual exclusion of different threads in different nodes .
- Reentrancy : If the same thread on the same node acquires the lock, it can acquire the lock again .
- Lock timeout : Support lock timeout as well as local lock , Prevent deadlock .
zookeeper Implement distributed locks
- zookeeper Distributed locks are based on
Temporary order nodeTo achieve - adopt session To prevent lock timeout
- zookeeper The temporary node of is automatically deleted after the client is disconnected , It can solve the deadlock problem
- When the sequence number of its own node is not the minimum , Through monitoring mechanism , Wait until the node number is the minimum , Blocking lock can be realized
- In creating the node is , The client writes its own information to the node , Get all , Judge by node information , Lock reentry can be realized
Redis Implement distributed locks
be based on SET NX EX Realization , Stand-alone version
Here use Redis set key It's a NX Parameters can be guaranteed in this key Write succeeded in the absence of . And add EX Parameter can make this key Automatically delete after timeout .
- Lock
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
public boolean tryLock(String key, String request) {
String result = this.jedis.set(LOCK_PREFIX + key, request, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, 10 * TIME);
if (LOCK_MSG.equals(result)){
return true ;
}else {
return false ;
}
}
- Unlock
Unlocking is also easy , In fact, this is key Delete it and everything will be fine , For example, use del key command .
public boolean unlock(String key,String request){
//lua script
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = null ;
if (jedis instanceof Jedis){
result = ((Jedis)this.jedis).eval(script, Collections.singletonList(LOCK_PREFIX + key), Collections.singletonList(request));
}else if (jedis instanceof JedisCluster){
result = ((JedisCluster)this.jedis).eval(script, Collections.singletonList(LOCK_PREFIX + key), Collections.singletonList(request));
}else {
//throw new RuntimeException("instance is error") ;
return false ;
}
if (UNLOCK_MSG.equals(result)){
return true ;
}else {
return false ;
}
}
be based on Redisson Realization , High availability version
Reference address :https://codechina.csdn.net/mirrors/redisson/redisson?utm_source=csdn_github_accelerator
// 1. The configuration file
Config config = new Config();
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379")
.setPassword(RedisConfig.PASSWORD)
.setDatabase(0);
//2. structure RedissonClient
RedissonClient redissonClient = Redisson.create(config);
//3. Set the lock resource name
RLock lock = redissonClient.getLock("redlock");
lock.lock();
try {
System.out.println(" Lock acquired successfully , Implement business logic ");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
Redis Distributed lock VS zookeeper Distributed lock
- zookeeper Reliability than redis Too much , It's just a little inefficient , If the amount of concurrency is not particularly large , The pursuit of reliability , The preferred zookeeper. For efficiency , Preferred redis Realization .
- zookeeper Distributed lock performance may not Redis The distributed lock is so high . Because every time you create a lock and release a lock , All need to be created dynamically 、 Destroy the instantaneous node to realize the lock function .zookeeper You can only create and delete nodes through Leader Server to execute , Then synchronize the data to all Follower On the machine .
- zookeeper Atomicity of is based on sequence=false Ensure node uniqueness ,redis Atomicity of is based on lua Script
- redis There may be data loss , because redis After the memory operation is successful, it returns directly success, At this time, data loss can be caused without flushing the disk, resulting in lock failure
边栏推荐
- 【C#】常用的Utils
- The difference between set and map
- Application du moteur de visualisation Web de topologie dans le domaine de la simulation et de l'analyse
- bisect模块
- @RequestBody
- Bisect module
- Huawei's general card identification function enables multiple card bindings with one key
- 10 database optimization best practices for web developers
- Quantum computing + semiconductor materials! Quantum and JSR reach cooperation
- 干货!手把手教你搭建高可用架构
猜你喜欢

Comment définir Notepad + + comme mode d'ouverture par défaut

MYSQL建表语句错误:1103-Incorrect table name

從數字化到智能運維:有哪些價值,又有哪些挑戰?

Canal realizes real-time synchronization of data from Mysql to es

Problems that enterprises need to pay attention to when creating product help centers!

CS5801_ HDMI to EDP advantage replaces lt6711a solution

MQ Series 2: technology selection of Message Oriented Middleware

如何將notepad++設置為默認打開方式

Diwen serial port screen tutorial (1)

函数高级应用
随机推荐
面对对象
MySQL CREATE TABLE statement error: 1103 incorrect table name
【LeetCode】26、删除有序数组中的重复项
R语言使用lm函数构建线性回归模型、使用I运算符嵌入表达式、使用表达式指定回归方程的形式
leetcode:74. 搜索二维矩阵
Problems that enterprises need to pay attention to when creating product help centers!
[MySQL learning notes 33] log
R language ggplot2 visualization: use the ggstripchart function of ggpubr package to visualize the dot strip plot, set the position parameter to configure the separation of different grouped data poin
医疗单据OCR识别+知识库校验,赋能保险智能理赔
論文中的好文佳句摘錄
Together with Alibaba cloud, grafana labs will provide the first grafana hosting service in China
Loj#576-「LibreOJ NOI Round #2」签到游戏【线段树】
After reading these five reasons, I finally know the reason why FTP was replaced
Extrait d'un bon article
Face the object
G1这么强,你确定不了解一下?
How to set notepad++ as the default opening method
【mysql学习笔记33】日志
The INI file configuration should be modified during Jerry's mode [chapter]
NVIDA CUDA-DirverAPI入门