当前位置:网站首页>常见分布式锁介绍
常见分布式锁介绍
2022-07-17 14:17:00 【西魏陶渊明】

作者: 西魏陶渊明
博客: https://blog.springlearn.cn/
西魏陶渊明
莫笑少年江湖梦,谁不少年梦江湖
西魏陶渊明
在单机环境下多线程操作共享数据时候回用到锁的概念,因为是单机可以直接使用jdk提供的锁机制就可以满足。
但是在微服务场景下,因为是多服务共享数据,此时jdk提供的锁就不能再使用了。于是乎就有了分布式锁。
本文介绍常见的几种可以使用的生产的分布式锁
本文面向有开发经验的同学,所以场景就不赘述,直接上干货
一、分布式锁具有的品格
- 基本的加锁和释放锁
- 具备锁失效机制,防止死锁
- 非阻塞机制
- 高性能和高可用
二、思考一下如何自己实现?
1. db
根据上面提出的要求,发现只要能满足多服务之前通信就能实现。
比如我们可以用mysql就能实现,比如A服务对一个表加锁和释放锁。B服务就会发现表加了锁。此时B就阻塞了。
当然这明显不满足,非阻塞的机制。另外如果要用一个数据库来做锁的场景也太浪费性能了。
2. redis
利用redis命令来实现,如果返回ok说明获取锁。返回nil说明没有获取到锁。
不阻塞,防止死锁,高性能,都满足
set key value [EX seconds] [PX milliseconds] [NX|XX]
EX seconds:设置失效时长,单位秒
PX milliseconds:设置失效时长,单位毫秒
NX:key不存在时设置value,成功返回OK,失败返回(nil)
XX:key存在时设置value,成功返回OK,失败返回(nil)
//对资源加一个锁 key为资源名 value可以为任意 ex为秒 1为过期时间 nx为
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
获取锁
- 在Zookeeper当中创建一个持久节点ParentLock。当第一个客户端想要获得锁时,需要在ParentLock这个节点下面创建一个临时顺序节点 Lock1。
- Client1查找ParentLock下面所有的临时顺序节点并排序,判断自己所创建的节点Lock1是不是顺序最靠前的一个。如果是第一个节点,则成功获得锁。
- 如果再有一个客户端 Client2 前来获取锁,则在ParentLock下载再创建一个临时顺序节点Lock2。
此时Client2发现自己并不是最靠前的就像Lock1注册了一个Watcher,用于监听Lock1节点释放。此时Client2就进入等待状态 - Client3,4以此类推
释放锁
- Client1释放了锁,此时Zookeeper就讲Lock1移出,并触发了Lock1的Watcher。
- Client2一直在监听Lock1的状态,当Lock1节点被删除,Client2里面收到通知获得了锁。
三、现成的解决方案
1. db的方式就不考虑了
实现简单,但是不划算,性能也不是最好的。
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) {
//连接redis
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
log.info("连接Redis");
//1.定义锁
RLock lock = redisson.getLock("myTest001");
try {
//尝试加锁的超时时间
Long timeout = 300L;
//锁过期时间
Long expire = 30L;
//2.获取锁
if (lock.tryLock(timeout, expire, TimeUnit.MILLISECONDS)) {
//2.1.获取锁成功的处理
log.info("加锁成功");
//...do something
log.info("使用完毕");
} else {
//2.2.获取锁失败的处理
log.info("加锁失败");
log.info("其他处理");
}
} catch (InterruptedException e) {
log.error("尝试获取分布式锁失败", e);
} finally {
//3.释放锁
try {
lock.unlock();
log.info("锁释放成功");
} catch (Exception e) {
//do nothing...
}
}
//关闭连接
redisson.shutdown();
log.info("关闭redis连接");
}
}
通过官方文档能找到实现第三方工具

3. zookeeper
<!-- 对zookeeper的底层api的一些封装 -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.12.0</version>
</dependency>
<!-- 封装了一些高级特性,如:Cache事件监听、选举、分布式锁、分布式Barrier -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.12.0</version>
</dependency>
几乎对所有的JDK锁都实现了,基于Zookeeper的分布式锁。具体使用方法可以自行百度。
- InterProcessMutex:分布式可重入排它锁
- InterProcessSemaphoreMutex:分布式排它锁
- InterProcessReadWriteLock:分布式读写锁
- InterProcessMultiLock:将多个锁作为单个实体管理的容器
- InterProcessSemaphoreV2 信号量
- DistributedBarrier 分布式栅栏
- DistributedDoubleBarrier 分布式栅栏
最后求关注,求订阅,谢谢你的阅读!
边栏推荐
- The case has been solved --- no matter how to change the code from the logic of MQ consumption, it will not take effect
- LOJ 2324 - "Tsinghua training 2017" small y and binary tree
- E-commerce sales data analysis and prediction (date data statistics, daily statistics, monthly statistics)
- Journal日志与oplog日志的区别
- Win10的环境变量配置
- Efficient space-based computing technology for satellite communication in 6g
- LeetCode 2335. Minimum total time required to fill the cup
- 玩转CANN目标检测与识别一站式方案
- Qt 两个重载QListWidget控件对象实现selectitem drag拖拽
- Documents required for military product development process - advanced version
猜你喜欢

(1) Learn about MySQL

LeetCode 558. 四叉树交集

人大、微软等提出InclusiveFL:异构设备上的包容性联邦学习

Powercli script performance optimization

A fastandrobust convolutionalneuralnetwork-based defect detection model inproductqualitycontrol-阅读笔记

LeetCode 2319. Judge whether the matrix is an X matrix

Tencent cloud server uses image to deploy WordPress personal website!

A fastandrobust convolutionalneuralnetwork-based defect detection model inproductqualitycontrol-閱讀筆記

Avi Deployment Guide (2): overview of AVI architecture

Journal日志与oplog日志的区别
随机推荐
Detailed explanation of Euler angle, axis angle, quaternion and rotation matrix
After summarizing the surface based knowledge of the database
Cmake common commands (V)
Mysql优化系列之limit查询
Rotation in unity3d
Thinking about the integrated communication of air, space and earth based on the "7.20 Zhengzhou rainstorm"
QT two overloaded qlistwidget control objects implement selectitem drag drag
Unity Dropdown(可编辑,可输入)下拉选择框,带文本联想
(二)使用MySQL
Pytoch framework learning record 1 cifar-10 classification
Mobile keyboard (simulation question)
vulnhub inclusiveness: 1
At5147-[agc036d]negative cycle [DP, model conversion]
Input number pure digital input limit length limit maximum value
最大半连通子图(tarjan缩点+拓扑排序+dp最长链)
每日刷题记录 (二十六)
Journal日志与oplog日志的区别
军品研制过程所需文件-进阶版
Evaluation method of machine learning model
Maximal semi connected subgraph (tarjan contraction + topological ordering + DP longest chain)