当前位置:网站首页>Redis distributed lock
Redis distributed lock
2022-07-27 23:39:00 【Fruit brother】
There are three implementation methods of distributed lock :
- Implementation of distributed lock based on Database ;
- Cache based (Redis etc. ) Implement distributed locks ;
- be based on Zookeeper Implement distributed locks ;
- article :https://www.cnblogs.com/xiaozengzeng/p/12641153.html
Cache based (Redis etc. ) Implement distributed locks
- Introduction to using commands :
(1)SETNX
SETNX key val: If and only if key When there is no ,set One key by val String , return 1; if key There is , Then do nothing , return 0.
(2)expire
expire key timeout: by key Set a timeout , Unit is second, After this time, the lock will release automatically , Avoid deadlock .
(3)delete
delete key: Delete key
In the use of Redis When implementing distributed locks , These three commands are mainly used .
- Realization thought :
(1) When getting the lock , Use setnx Lock , 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 .
(2) When acquiring the lock, a timeout for acquiring is also set , If it exceeds this time, give up acquiring lock .
(3) When you release the lock , adopt UUID Decide whether to lock , If it's time to lock , execute delete Lock release .
Redis Locks mainly use Redis Of setnx command .
- Lock command :SETNX key value, When the key doesn't exist , Set the key and return success , Otherwise return to failure .KEY It's the only sign of the lock , Generally, the name is decided by business .
- Unlock command :DEL key, Release the lock by deleting key value pairs , So that other threads can pass through SETNX Command to get the lock .
- Lock timeout :EXPIRE key timeout, Set up key Timeout for , To ensure that even if the lock is not explicitly released , The lock can also be released automatically after a certain period of time , Avoid locking resources forever .
if (setnx(key, 1) == 1){
expire(key, 30)
try {
//TODO Business logic
} finally {
del(key)
}
}
One 、 What is distributed lock ?
To introduce distributed locks , First of all, it should be mentioned that the thread lock is corresponding to the distributed phase lock 、 Process lock .
Thread lock : Mainly used to give methods 、 Code block lock . When a method or code uses a lock , Only one thread executes the method or the code segment at the same time . Thread lock only in the same JVM Effective , Because the implementation of thread lock depends on the shared memory between threads , such as synchronized Is the shared object header , Display lock Lock Is to share a variable (state).
Process lock : In order to control multiple processes in the same operating system to access a shared resource , Because the process is independent , Individual processes cannot access resources of other processes , So it can't pass synchronized Implement process lock with equal thread lock .
Distributed lock : When multiple processes are not in the same system , Using distributed lock to control the access of multiple processes to resources .
When we modify existing data in the system , Need to read first , Then modify and save , It's easy to run into concurrency problems at this point . Because modifying and saving are not atomic operations , In a concurrent scenario , Some operations on data may be lost . In a single server system, we often use local locks to avoid concurrency problems , However , When services are deployed in a cluster mode , Local lock cannot work between multiple servers , In this case, the distributed lock is needed to ensure the data consistency .
Atomicity : That is, an operation or multiple operations are all executed and the execution process will not be interrupted by any factors , Or they don't do it . stay Java in , Reading and assigning variables of basic data type is atomic operation , That is, these operations cannot be interrupted , Or execute , Or not .
When we modify existing data in the system , Need to read first , Then modify and save , It's easy to run into concurrency problems at this point . Because modifying and saving are not atomic operations ,** In a concurrent scenario , Some operations on data may be lost .** In a single server system, we often use local locks to avoid concurrency problems , However , When services are deployed in a cluster mode , Local lock cannot work between multiple servers , In this case, the distributed lock is needed to ensure the data consistency .
https://segmentfault.com/a/1190000038330434
Redis Distributed lock
Redis Locks mainly use Redis Of setnx command .
- Lock command :SETNX key value, When the key doesn't exist , Set the key and return success , Otherwise return to failure .KEY It's the only sign of the lock , Generally, the name is decided by business .
- Unlock command :DEL key, Release the lock by deleting key value pairs , So that other threads can pass through SETNX Command to get the lock .
- Lock timeout :EXPIRE key timeout, Set up key Timeout for , To ensure that even if the lock is not explicitly released , The lock can also be released automatically after a certain period of time , Avoid locking resources forever .
if (setnx(key, 1) == 1){
expire(key, 30)
try {
//TODO Business logic
} finally {
del(key)
}
}
边栏推荐
- 一位软件投资者的独白:我为什么不追逐快速增长的公司
- 许锦波:AI蛋白质预测与设计
- NDK 系列(6):说一下注册 JNI 函数的方式和时机
- Nature review: preferential effects in the formation of microbial communities
- 【12月海口】2022年第六届船舶,海洋与海事工程国际会议(NAOME 2022)
- 【软考软件评测师】2014综合知识历年真题
- 消息队列常见的几种使用场景介绍
- C # delegate usage -- console project, which implements events through delegation
- Interviewer: let's talk about the specific process of network data transmission
- iMeta | 国际标准刊号ISSN印刷版正式确认,双ISSN申请完成
猜你喜欢

置信区间之正态

他山之石 | 蚂蚁超大规模知识图谱构建及应用

iMeta | 国际标准刊号ISSN印刷版正式确认,双ISSN申请完成

Normality of confidence interval

Ideas, methods and steps of making folding fans with 3DMAX
![[soft test software evaluator] 2014 comprehensive knowledge over the years](/img/85/46c8fc696ae5249a9aca22b50493f0.jpg)
[soft test software evaluator] 2014 comprehensive knowledge over the years
软件测试功能测试全套常见面试题【功能测试】面试总结4-2

Learn more about xxE injection

我年薪100万,全身上下没有超过100块的衣服:存钱,是最顶级的自律

深入了解 XXE 注射
随机推荐
ZCMU--1720: 死亡如风,我要装逼
消息队列常见的几种使用场景介绍
What is the MySQL data storage method?
Software test function test full set of common interview questions [function test] interview summary 4-2
总投资600亿!富士康半导体高端封测项目正式落户青岛
请求合并哪家强——接口请求合并的3种技巧,性能直接爆表
2022夏暑假每日一题(五)
苹果发布新款iPhone SE:搭载A13仿生处理器,售价3299元起
【 图像去雾】基于暗通道和非均值滤波实现图像去雾附matlab代码
Figure basic knowledge code
js数组复制速度测试220320
With double-digit growth in revenue and profit, China Resources Yibao has quietly created these new products worth more than 100 million
In 2019, the world's top ten semiconductor manufacturers: Intel returned to the first place, and apple rose sharply against the trend
Visual display method of machine learning project
[GNN report] Tang Jian, Montreal, Canada: Geometric deep learning for drug discovery
NDK 系列(6):说一下注册 JNI 函数的方式和时机
进制转换方法
他山之石 | 蚂蚁超大规模知识图谱构建及应用
怎么使用C# Winform实现复制文件显示进度
【JS 逆向百例】某公共资源交易网,公告 URL 参数逆向分析