当前位置:网站首页>Implementation of redis distributed lock
Implementation of redis distributed lock
2022-08-04 08:15:00 【Zero shear】
I. Introduction
When we modify the existing data in the system, we need to read it first, and then modify and save it. At this time, it is easy to encounter concurrency problems.Since modification and saving are not atomic operations, some operations on data may be lost in concurrent scenarios.In a single-server system, we often use local locks to avoid problems caused by concurrency. However, when services are deployed in a cluster, local locks cannot take effect between multiple servers. At this time, distributed locks are required to ensure data consistency.accomplish.

Second, the mainstream implementation scheme of distributed locks
Distributed lock based on database
Cache based (Redis, etc.)
Based on Zookeeper
Each distributed lock solution has its own advantages and disadvantages:
Performance: redis is the highest
Reliability: zookeeper highest
3. Implementing distributed locks based on redis
Redis locks mainly use Redis's setnx command
- Locking command: SETNX key value, when the key does not exist, set the key and return success, otherwise return failure.KEY is the unique identifier of the lock, which is generally named according to the business.
- Unlock command: DEL key, releases the lock by deleting the key-value pair, so that other threads can acquire the lock through the SETNX command.
- Lock timeout: EXPIRE key second, set the timeout time of the key to ensure that even if the lock is not explicitly released, the lock can be automatically released after a certain period of time to avoid the resource being locked forever.
There are some problems with the above lock implementation:
1-SETNX-and-EXPIRE-non-atomic
If SETNX is successful, after setting the lock timeout time, the server hangs up, restarts or has network problems, etc., resulting in the EXPIRE command not being executed, and the lock becoming deadlock if the lock timeout time is not set.
Solution:
1. Use Lua script to compose SETNX and EXPIRE into atomic operation
2. Use set key value ex second nx
2, lock removal
If thread A successfully acquires the lock and sets an expiration time of 30 seconds, but the execution time of thread A exceeds 30 seconds, the lock is automatically released after expiration, and thread B acquires the lock at this time; then the execution of A is completed, and thread A usesDEL command to release the lock, but the lock added by thread B has not been executed yet, and the lock added by thread B is actually released by thread A.
Solution:
When set acquires the lock, set a specified unique value (for example: uuid), and acquire this before releasingvalue, determine whether it is your own lock, and if so, release the lock

3. Timeout unlocking leads to concurrency (similar to the previous problem)
If thread A successfully acquires the lock and sets the expiration time to 30 seconds, but the execution time of thread A exceeds 30 seconds, the lock expires and is automatically released. At this time, thread B acquires the lock, and thread A and thread B execute concurrently.

Concurrency of two threads A and B is obviously not allowed. Generally, there are two ways to solve this problem:
- Set the expiration time long enough to ensure that the code logic can complete before the lock is released.
- Add a daemon thread for the thread that acquires the lock, and increase the valid time for the lock that will expire but not be released.
4. The deletion operation lacks atomicity
If thread A successfully acquires the lock and sets the expiration time to 30 seconds, but the execution time of thread A is exactly 30 seconds, the lock is automatically released when it expires. At this time, A just completes the business logic and makes a judgment to release the lock.But before the lock is released, thread B acquires the lock again, and then thread A uses the DEL command to release the lock, but the lock added by thread B has not been executed yet, and the lock added by thread B actually released by thread A.
Solution:
Use Lua scripts to ensure atomicity of locking and releasing locks.
5. How does Lua script ensure its atomicity
Redis embeds a lua environment (very small) to run lua scripts. When running lua scripts, other steps and commands will not be run. It is similar to adding locks to the code executing lua scripts, so its atomicity is guaranteed..
Four. Summary
To ensure that distributed locks are available, we at least make sureThe implementation of the lock also satisfies the following four conditions:
- Mutually exclusive.At any time, only one client can hold the lock.
- No deadlock occurs.Even if a client crashes while holding the lock and does not actively unlock it, it is guaranteed that other clients can lock in the future.
- The ringer must also be tied to the bell.Locking and unlocking must be done by the same client, and the client cannot unlock the locks added by others.
- Locking and unlocking must be atomic.
边栏推荐
- 高等代数_证明_对称矩阵属于不同特征值的特征向量正交
- Mysql insert on duplicate key 死锁问题定位与解决
- 经典动态规划问题的递归实现方法——LeetCode39 组合总和
- 大佬们,mysql里text类型的字段,FlinkCDC需要特殊处理吗 就像处理bigint uns
- 金仓数据库的单节点如何转集群?
- 大家好,请教一个问题啊,我们通过flinkcdc把Oracle数据同步到doris,目前的问题是,只
- 最近的一些杂感-20220731
- MYSQL JDBC图书管理系统
- [STM32] STM32F103 series name and package, memory
- Secondary network security competition C module MS17-010 batch scanning
猜你喜欢
随机推荐
sql在字段重复时 对某个字段根据最新时间取数
Use of MotionLayout
金仓数据库KingbaseES客户端编程接口指南-JDBC(7. JDBC事务处理)
新特性解读 | MySQL 8.0 在线调整 REDO
redis分布式锁的实现
js异步变同步、同步变异步
LeetCode 97. 交错字符串
<jsp:useBean>动作的使用
[Computer recording screen] How to use bandicam to record the game setting graphic tutorial
第一次用postgreSQL,想装主从,用的12.7 tar.gz版本。安装好后没在 share目录下找到样例配置recovery.conf.sample,是安装方式不对,还是路径不对?
24.循环神经网络RNN
一天学会JDBC04:ResultSet的用法
IntelliJ新建一个类或者包的快捷键是什么?
Thread类的基本使用。
【Attention】Dual Attention(DANet) & Fully Attention(FLA)
YOLOv5应用轻量级通用上采样算子CARAFE
ShowMeAI —— Show u 三连
字符流与字节流的区别
实现加载驱动、得到数据库对象、关闭资源的代码复用,将代码提取到相应的工具包里边。优化程序
【NOI模拟赛】纸老虎博弈(博弈论SG函数,长链剖分)








