当前位置:网站首页>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 !
边栏推荐
- Introduction to sap appgyver
- 如何在 RHEL 9 中更改和重置忘记的root密码
- (1) Learn about MySQL
- Pytoch learning record 2 linear regression (tensor, variable)
- 每日刷题记录 (二十六)
- 2022/7/16
- 466-82(3、146、215)
- SSM uses POI to export data to excel
- 论文笔记:Mind the Gap An Experimental Evaluation of Imputation ofMissing Values Techniques in TimeSeries
- 剑指 Offer II 041. 滑动窗口的平均值
猜你喜欢

常见分布式锁介绍

XSS.haozi.me刷题

leetcode-08

LeetCode 558. Intersection of quadtree

UE4 understanding of animation blueprint

一个报错, Uncaught TypeError: ModalFactory is not a constructor

Unity dropdown (editable, inputable) drop-down selection box with Text Association

Game theory (Depu) and investment (40/100)

(1) Learn about MySQL

LeetCode 2335. Minimum total time required to fill the cup
随机推荐
The type of MySQL index (single column index, combined index, BTREE index, clustered index, etc.)
LeetCode 558. 四叉树交集
Develop the first Flink app
Integrated network architecture and network slicing technology of air, earth and sea
input number 純數字輸入 限制長度 限制 最大值
LeetCode 745. Prefix and suffix search
每日刷题记录 (二十六)
Pytoch and weight decay (L2 norm)
SSM uses POI to export data to excel
Discussion on Euler angle solution of rocket large maneuvering motion
PPDE第二季度迎新 | 欢迎22位AI开发者加入飞桨开发者技术专家计划!
Tier defect detection using full revolutionary network
要想组建敏捷团队,这些方法不可少
Sword finger offer II 041 Average value of sliding window
Pytoch framework learning record 1 cifar-10 classification
LeetCode 558. Intersection of quadtree
Huawei machine test: Message decompression
Introduction to sap appgyver
(1) Learn about MySQL
8.固定收益投资