当前位置:网站首页>Laravel 实现redis分布式锁
Laravel 实现redis分布式锁
2022-08-04 23:06:00 【陈卿诺语】
Redis几种架构
Redis发展到现在,几种常见的部署架构有:
单机模式;
主从模式;
哨兵模式;
集群模式;
从分布式锁的角度来说, 无论是单机模式、主从模式、哨兵模式、集群模式,其原理都是类同的。 只是主从模式、哨兵模式、集群模式的更加的高可用、或者更加高并发。
所以,接下来先基于单机模式,基于Jedis手工造轮子实现自己的分布式锁。
首先看两个命令:
Redis分布式锁机制,主要借助setnx和expire两个命令完成。
setnx命令:
SETNX 是SET if Not eXists的简写。将 key 的值设为 value,当且仅当 key 不存在; 若给定的 key 已经存在,则 SETNX 不做任何动作。
下面为客户端使用示例:
127.0.0.1:6379> set lock "unlock"
OK
127.0.0.1:6379> setnx lock "unlock"
(integer) 0
127.0.0.1:6379> setnx lock "lock"
(integer) 0
127.0.0.1:6379> expire命令:
expire命令为 key 设置生存时间,当 key 过期时(生存时间为 0 ),它会被自动删除. 其格式为:
EXPIRE key seconds
下面为客户端使用示例:
127.0.0.1:6379> expire lock 10
(integer) 1
127.0.0.1:6379> ttl lock
8 $lock = Redis::setnx('cqny',5,1);
if(!$lock) return $this->apiError('操作太频繁了');
Redis::expire('cqny',10); $block = Cache::lock("GoodLock",10); //返回一个redis对象
if ($block){
// Todo 业务逻辑
sleep(10);
echo "业务逻辑<br>";
$block->release(); // 释放锁
return "秒杀成功";
}
return 12;
$suo = Redis::set('123',123,"nx","ex",5);
if ($suo) Redis::del('123');
边栏推荐
- Based on the results of the facts
- [Cultivation of internal skills of memory operation functions] memcpy + memmove + memcmp + memset (4)
- Jbpm3.2 开发HelloWorld (简单请假流程)客户端
- MySQL的JSON 数据类型1
- 被领导拒绝涨薪申请,跳槽后怒涨9.5K,这是我的心路历程
- 【3D建模制作技巧分享】ZBrush模型如何添加不同材质
- 当panic或者die被执行时,或者发生未定义指令时,如何被回调到
- kernel问题定位手段总结
- MySQL基础篇【子查询】
- 社区分享|腾讯海外游戏基于JumpServer构建游戏安全运营能力
猜你喜欢

SSM整合完整流程讲解

【3D建模制作技巧分享】ZBrush模型制作流程:地精

MySQL的安装与卸载

社区分享|腾讯海外游戏基于JumpServer构建游戏安全运营能力

【3D建模制作技巧分享】ZBrush纹理贴图怎么导入

Reconfigure the ffmpeg plugin in chrome

If you can't get your heart, use "distributed lock" to lock your people

线上虚拟展馆展示具有哪些优势

为何越来越多人选择进入软件测试行业?深度剖析软件测试的优势...
![[Cultivation of internal skills of memory operation functions] memcpy + memmove + memcmp + memset (4)](/img/08/e115e1b0d801fcebef440ad4932610.png)
[Cultivation of internal skills of memory operation functions] memcpy + memmove + memcmp + memset (4)
随机推荐
The market value of 360 has evaporated by 390 billion in four years. Can government and enterprise security save lives?
【云原生 · Kubernetes】Kubernetes运维
Both synchronized and ReentrantLock are smooth, because they are reentrant locks, and a thread will not deadlock if it takes the lock multiple times. We need reentrant locks
【字符串函数内功修炼】strncpy + strncat + strncmp(二)
Latex fast insert author ORCID
【3D建模制作技巧分享】ZBrush如何设置笔刷快捷键
Service Mesh落地路径
一点点读懂thermal(一)
xss总结
PZK学C语言之字符串函数(一)
typeScript-promise
Since a new byte of 20K came out, I have seen what the ceiling is
PID Controller Improvement Notes No. 7: Improve the anti-overshoot setting of the PID controller
Redis understanding
Shell expect 实战案例
Literature reading ten - Detect Rumors on Twitter by Promoting Information Campaigns with Generative Adversarial Learn
智慧养老整体解决方案
Using ngrok to optimize web pages on raspberry pi (2)
轮播图动态渲染
VC bmp文件总结