当前位置:网站首页>从源码角度剖析redis分布式锁
从源码角度剖析redis分布式锁
2022-04-21 07:07:00 【dengk2013】


解决思路:需要自己加的锁自己解锁,通过线程id来判断是否是自己加的锁


这样做的话:重现刚刚说的问题:比如第一个线程执行了15s,此时第一个线程已经释放了锁,第二个线程拿到了锁,需要执行8s,当执行到第5s,第一个线程执行玩了,需要释放锁,判断当前的clientId和redis的不一样,所以不会释放锁,也就是不会删除第二个线程的锁,当第二个线程执行玩了,释放锁能成功,这就起到了锁的作用,自己加的锁,自己释放,第一个线程由于超时早就释放锁了,所以就不会影响下一个线程去争抢锁
但是有有新的问题:如何保证锁周期类业务代码执行完?
通过锁续命来增加锁的时间,比如可以通过定时任务来检查加锁时间快结束,我们增加加锁的时间,这样就可以保证在锁的周期来完成业务代码
3行代码解决分布式锁:redission组件的使用




每个10s检测是否还有锁,如果锁还存在直接设置该锁的时间为30s
对于上述redis主从架构存在的问题:第一个线程进来后抢到锁,加锁也成功了,此时redis在做主从的时候主节点宕机了,导致从节点没有来得及复制,也就是从节点没有key,那么主从节点从新选举的时候,从节点变成了主节点,主节点没有key,此时第二个线程进来后仍然可以加锁成功,也就是一个产品可能被枷锁2次,导致超卖的问题,当然这种概率几乎为0,当然我们也可以通过zk分布式锁可以解决主从节点失效带来的问题
如何提高分布式锁的效率?对redis中的key进行分段存储,比如有A商品有100个,redis存放可以这样存放: A_001=1000可以这样设置key,A001_1=100,A001_2=100,A001_3=100,....这样通过分段锁可以大大提高效率
版权声明
本文为[dengk2013]所创,转载请带上原文链接,感谢
https://blog.csdn.net/u012222011/article/details/124293865
边栏推荐
- 上古神器Vim
- 信息学奥赛一本通 1209:分数求和 | OpenJudge 1.13 12:分数求和
- Technical background and practical role of "industrial digitization"
- 显示器选购参考天梯
- Introduction to zephyr 1.0 of Internet of things operating system zephyr (Introduction)
- Actual JDBC connection to MySQL database
- 【以太网交换安全】--- 端口隔离运行原理及二层隔离三层通信实例配置讲解
- PHP format numbers
- 实战JDBC连接Mysql数据库
- . net core throws an error and writes it Txt file
猜你喜欢

Build openwrt file system for i.mx6q development board

【项目】小帽外卖(六)

Shortcut keys for batch modification of variable name and batch replacement code in idea

结合实际聊聊防反接电路(防反接电路总结)

Fuzzy query between two tables of SQL server and steps of importing Excel data into SQL Server

路由器设备选型参照天梯

在Win10系统中用mimikatz抓取明文密码

Advanced C language pointer (1. First and second order pointers)

【2022DASCTF X SU】 三月春季挑战赛 web复现

Valentina Studio Pro for Mac(mac数据库管理软件)
随机推荐
Hackmyvm integrated target | driftingblues-9 (end)
【以太网交换安全】--- 端口隔离运行原理及二层隔离三层通信实例配置讲解
【以太网交换安全】---端口安全及MAC地址飘移防止与检测
Fuzzy query between two tables of SQL server and steps of importing Excel data into SQL Server
Win10 提示账户名与安全标识间无任何映射完成
You cannot set a form field before rendering a field associated with the value
如何修改 Rancher Server 的 IP 地址
动态规划--LC474.一和零
Couchdb-垂直越权
Server deployment SVN environment
The listview column in C automatically adapts to the perfect effect of scaling
PHP format numbers
数据库实验一、数据库的创建及基本查询
树的基本概念与存储结构
Replication of Apache Solr Remote Code Execution Vulnerability (cve-2019-0193)
Actual combat of cloud native kubesphere multi tenant system
It can switch the aircraft duel with three interfaces of start, battle and settlement, modularization, pyGame, rect and exe packaging
Annotation function supplement
PHP two-dimensional array to one-dimensional array
. net core throws an error and writes it Txt file