当前位置:网站首页>Introduction to common distributed locks
Introduction to common distributed locks
2022-07-19 11:17:00 【TaoYuanming of the Western Wei Dynasty】

author : TaoYuanming of the Western Wei Dynasty
Blog : https://blog.springlearn.cn/
TaoYuanming of the Western Wei Dynasty
Don't laugh at the young Jianghu dream , Who doesn't dream of Jianghu
TaoYuanming of the Western Wei Dynasty
In the stand-alone environment, the concept of lock is used when multithreading operates to share data , Because a single machine can be used directly jdk The locking mechanism provided can meet .
But in the microservice scenario , Because multiple services share data , here jdk The lock provided can no longer be used . So there are distributed locks .
This article introduces several common distributed locks that can be used in production
This article is for students with development experience , So I won't repeat the scene , Direct delivery of dry goods
One 、 The character of distributed lock
- Basic locking and unlocking
- Lock failure mechanism , Prevent deadlock
- Non blocking mechanism
- High performance and high availability
Two 、 Think about how to realize it by yourself ?
1. db
According to the above requirements , It is found that communication can be achieved as long as multiple services can be met .
For example, we can use mysql Can achieve , such as A The service locks and unlocks a table .B The service will find that the table is locked . here B It's blocking .
Of course, this is obviously not satisfied , Non blocking mechanism . In addition, if you want to use a database as a locking scenario, it is also a waste of performance .
2. redis
utilize redis Command to implement , If you return ok Description acquire lock . return nil Indicates that the lock was not acquired .
Don't block , Prevent deadlock , High performance , All satisfied with
set key value [EX seconds] [PX milliseconds] [NX|XX]
EX seconds: Set the failure duration , Unit second
PX milliseconds: Set the failure duration , Unit millisecond
NX:key Set when not present value, Successfully returns OK, Failure to return (nil)
XX:key Set when it exists value, Successfully returns OK, Failure to return (nil)
// Put a lock on the resource key Name the resource value It can be anything ex Seconds 1 For expiration time nx by
127.0.0.1:6379> set ziyuanming 1 ex 1 nx
OK
127.0.0.1:6379> set ziyuanming 1 ex 1 nx
(nil)
3. zookeeper
Get the lock
- stay Zookeeper Create a persistent node ParentLock. When the first client wants to acquire a lock , Need to be in ParentLock Create a temporary sequence node under this node Lock1.
- Client1 lookup ParentLock All of the following temporary order nodes and sort , Judge the nodes you create Lock1 Is it the top of the order . If it's the first node , The lock is obtained successfully .
- If there is another client Client2 Come and get the lock , It's in ParentLock Download and create a temporary sequence node Lock2.
here Client2 Finding that you are not at the top is like Lock1 Registered a Watcher, For monitoring Lock1 Node release . here Client2 It will enter the waiting state - Client3,4 And so on
Release the lock
- Client1 Lock released , here Zookeeper Just talk Lock1 Removed from the , And triggered Lock1 Of Watcher.
- Client2 Been listening Lock1 The state of , When Lock1 The node is deleted ,Client2 I received the notice and got the lock .
3、 ... and 、 Off the shelf solutions
1. db The way is not considered
Implement a simple , But it's not cost-effective , The performance is not the best .
2. redis
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.0</version>
</dependency>
public class RedLockTester {
public static void main(String[] args) {
// Connect redis
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
log.info(" Connect Redis");
//1. Definite lock
RLock lock = redisson.getLock("myTest001");
try {
// Timeout for trying to lock
Long timeout = 300L;
// Lock expiration time
Long expire = 30L;
//2. Get the lock
if (lock.tryLock(timeout, expire, TimeUnit.MILLISECONDS)) {
//2.1. Successful lock acquisition
log.info(" Locking success ");
//...do something
log.info(" After use ");
} else {
//2.2. Processing of lock acquisition failure
log.info(" Locking failed ");
log.info(" Other treatments ");
}
} catch (InterruptedException e) {
log.error(" Attempt to acquire distributed lock failed ", e);
} finally {
//3. Release the lock
try {
lock.unlock();
log.info(" Lock released successfully ");
} catch (Exception e) {
//do nothing...
}
}
// Close the connection
redisson.shutdown();
log.info(" close redis Connect ");
}
}
Third party tools can be found and implemented through official documents

3. zookeeper
<!-- Yes zookeeper The bottom of the api Some of the packages -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.12.0</version>
</dependency>
<!-- Encapsulates some advanced features , Such as :Cache Event monitoring 、 The election 、 Distributed lock 、 Distributed Barrier -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.12.0</version>
</dependency>
For almost all JDK The lock has been realized , be based on Zookeeper Distributed locks for . Specific use method can by oneself baidu .
- InterProcessMutex: Distributed reentrant exclusive lock
- InterProcessSemaphoreMutex: Distributed exclusive lock
- InterProcessReadWriteLock: Distributed read and write locks
- InterProcessMultiLock: Manage multiple locks as containers for a single entity
- InterProcessSemaphoreV2 Semaphore
- DistributedBarrier Distributed fence
- DistributedDoubleBarrier Distributed fence
Finally, please pay attention , Request subscription , Thanks for reading !
边栏推荐
- Over fitting and under fitting
- input number 純數字輸入 限制長度 限制 最大值
- Pytorch. NN implementation of multi-layer perceptron
- Detailed explanation of multiple linear regression
- Introduction to the universal theme system of SAP appgyver
- SSM使用poi将数据导出到excel
- IP SAN has an independent file system. After the application server accesses the IP SAN through the network sharing protocol, it can read and write the files in the file system
- Antd drop-down multiple options to transfer values to the background for query operations
- A fastandrobust convolutionalneuralnetwork-based defect detection model inproductqualitycontrol-阅读笔记
- OA系统与MES系统的异同点
猜你喜欢

Svn learning

Tencent cloud server uses image to deploy WordPress personal website!

Pytoch and weight decay (L2 norm)

Discussion on Euler angle solution of rocket large maneuvering motion

LeetCode 2249. Count the number of grid points in the circle

Journal日志与oplog日志的区别

Win10安装Apache Jena 3.17
![Some methods of early MCU encryption [get data in the comment area]](/img/14/8e1dcb799d8a3c0aefcac09be9dc51.png)
Some methods of early MCU encryption [get data in the comment area]

Limit query of MySQL optimization series

Antd drop-down multiple options to transfer values to the background for query operations
随机推荐
Nombre d'entrées nombre d'entrées numériques pures limite de longueur maximale
leetcode-08
Un modèle de détection par défaut basé sur le réseau neuronal évolutif rapide dans le contrôle de la qualité des produits - lire les notes
Documents required for military product development process - advanced version
Set the interface language of CMD command prompt window to English
Introduction to virtualization troubleshooting
Summary of port mirroring methods with VDS or NSX under vSphere
AT5147-[AGC036D]Negative Cycle【dp,模型转换】
Mysql优化系列之limit查询
Unity dropdown (editable, inputable) drop-down selection box with Text Association
如何在 RHEL 9 中更改和重置忘记的root密码
Game theory (Depu) and investment (40/100)
树链剖分思想讲解 + AcWing 2568. 树链剖分(dfs序 + 爬山法 + 线段树)
SVN学习
Mysql 自增id、uuid与雪花id
Thinking about the integrated communication of air, space and earth based on the "7.20 Zhengzhou rainstorm"
Future applications and technical challenges of backscatter communication
论文笔记:Mind the Gap An Experimental Evaluation of Imputation ofMissing Values Techniques in TimeSeries
6G smart endogenous: technical challenges, architecture and key features
(1) Learn about MySQL