当前位置:网站首页>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)
}
}
边栏推荐
- 进制转换方法
- 四次挥手的Socket交互流程
- Current situation and future of Nb IOT industry: cross the threshold of 100million shipments and rush to 5g connection!
- [signal processing] weak signal detection in communication system based on the characteristics of high-order statistics with matlab code
- 西门子PLC能否实时无线采集多处从站模拟量数据?
- 远程调试 idea配置remote debug、在远程服务器的程序中,添加JVM启动参数-Xdebug
- What are the methods of process synchronization?
- 【C语言】通讯录(动态版本)
- 7.6万人停工!东芝宣布关闭日本所有工厂
- What is the difference between concurrency and parallelism?
猜你喜欢

Ideas, methods and steps of making folding fans with 3DMAX

远程调试 idea配置remote debug、在远程服务器的程序中,添加JVM启动参数-Xdebug

【软考软件评测师】2014综合知识历年真题

如何快捷地查看H.265视频播放器EasyPlayer的API属性及其使用方法?

深入了解 XXE 注射

Implicit indicators for evaluating the advantages and disadvantages of automated testing
![[soft test software evaluator] 2014 comprehensive knowledge over the years](/img/85/46c8fc696ae5249a9aca22b50493f0.jpg)
[soft test software evaluator] 2014 comprehensive knowledge over the years

Bi Shi - University Logistics Management System Based on SSM

QT with OpenGL(Shadow Mapping)(平行光篇)

How to quickly view the API properties and usage of the h.265 video player easyplayer?
随机推荐
【GNN报告】加拿大蒙特利尔唐建:Geometric Deep Learning For Drug Discovery
2022年土木,建筑与环境工程国际会议(ICCAEE 2022)
技术认证 | 图扑软件携手华为云再创合作共赢新局面
【 图像去雾】基于暗通道和非均值滤波实现图像去雾附matlab代码
reduce错误示范
Solve 5g pain points, Meizu 17 smart 5g fast and stable technology release
Zabbix4.0使用SNMP代理方式监控vcenter6.5
2019年全球十大半导体厂商:英特尔重回第一,苹果逆势大涨
并发和并行有什么区别?
总投资600亿!富士康半导体高端封测项目正式落户青岛
Huawei Hongmeng 3 was officially released, and this security feature has solved a major pain point
With double-digit growth in revenue and profit, China Resources Yibao has quietly created these new products worth more than 100 million
Reinforcement learning - pytorch realizes advantage actor critical (A2C)
[signal denoising] signal denoising based on Kalman filter with matlab code
日产1500万只!比亚迪口罩拿下美国加州10亿美元订单
置信区间之正态
Preliminary understanding of Panda3D audio and advanced interactive components
【C语言】通讯录(动态版本)
【信号去噪】基于卡尔曼滤波实现信号去噪附matlab代码
详解分布式系统的幂等