Redis从入门到精通-分布式锁-代码实现
一、代码基本实现
package com.angoubiubiu.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class RedisController { @Autowired private RedisTemplate redisTemplate; @GetMapping("/redis") public String testRedis() { //设置值到redis redisTemplate.opsForValue().set("name","lucy"); //从redis获取值 String name = (String)redisTemplate.opsForValue().get("name"); return name; } /** * 测试加锁情况 */ @GetMapping("testLock") public void testLock(){ //1获取锁,setne Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "111"); //2获取锁成功、查询num的值 if(lock){ Object value = redisTemplate.opsForValue().get("num"); //2.1判断num为空return if(StringUtils.isEmpty(value)){ return; } //2.2有值就转成成int int num = Integer.parseInt(value+""); //2.3把redis的num加1 redisTemplate.opsForValue().set("num", ++num); //2.4释放锁,del redisTemplate.delete("lock"); }else{ //3获取锁失败、每隔0.1秒再获取 try { Thread.sleep(100); testLock(); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 测试不加锁情况 */ @GetMapping("noLock") public void noLock(){ Object value = redisTemplate.opsForValue().get("num"); //2.1判断num为空return if(StringUtils.isEmpty(value)){ return; } //2.2有值就转成成int int num = Integer.parseInt(value+""); //2.3把redis的num加1 redisTemplate.opsForValue().set("num", ++num); } }
1、测试加锁
Redis: set num 0
利用ab测试工具模拟并发
ab -n 100 -c 10 http://192.168.10.1:9001/testLock
此处报
Benchmarking 192.168.10.1 (be patient).....done
建议配redis连接池
# 最大可用连接数(默认为8,负数表示无限) spring.redis.jedis.pool.max-active=-1 # 从连接池中获取连接最大等待时间(默认为-1,单位为毫秒,负数表示无限) spring.redis.jedis.pool.max-wait=-1 # 最小空闲连接数(默认为0,该值只有为正数才有用) spring.redis.jedis.pool.min-idle=0 # 最大空闲连接数(默认为8,负数表示无限) spring.redis.jedis.pool.max-idle=-1
结果:100个请求 num的个数就有100个 成功
2、测试不加锁
ab -n 100 -c 10 http://192.168.10.1:9001/noLock
结果:100个请求 num的个数只有21个
基本实现。
问题:setnx刚好获取到锁,业务逻辑出现异常,导致锁无法释放
解决:设置过期时间,自动释放锁。
四、优化之设置锁的过期时间
package com.angoubiubiu.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.TimeUnit; @RestController public class RedisController { @Autowired private RedisTemplate redisTemplate; @GetMapping("/redis") public String testRedis() { //设置值到redis redisTemplate.opsForValue().set("name","lucy"); //从redis获取值 String name = (String)redisTemplate.opsForValue().get("name"); return name; } /** * 测试加锁情况 */ @GetMapping("testLock") public void testLock(){ //1获取锁,setne Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "111",3, TimeUnit.SECONDS);//3秒之后过期 //2获取锁成功、查询num的值 if(lock){ Object value = redisTemplate.opsForValue().get("num"); //2.1判断num为空return if(StringUtils.isEmpty(value)){ return; } //2.2有值就转成成int int num = Integer.parseInt(value+""); //2.3把redis的num加1 redisTemplate.opsForValue().set("num", ++num); //2.4释放锁,del redisTemplate.delete("lock"); }else{ //3获取锁失败、每隔0.1秒再获取 try { Thread.sleep(100); testLock(); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 测试不加锁情况 */ @GetMapping("noLock") public void noLock(){ Object value = redisTemplate.opsForValue().get("num"); //2.1判断num为空return if(StringUtils.isEmpty(value)){ return; } //2.2有值就转成成int int num = Integer.parseInt(value+""); //2.3把redis的num加1 redisTemplate.opsForValue().set("num", ++num); } }
压力测试肯定也没有问题。自行测试
问题:可能会释放其他服务器的锁。
场景:如果业务逻辑的执行时间是7s。执行流程如下
1. index1业务逻辑没执行完,3秒后锁被自动释放。
2. index2获取到锁,执行业务逻辑,3秒后锁被自动释放。
3. index3获取到锁,执行业务逻辑
4. index1业务逻辑执行完成,开始调用del释放锁,这时释放的是index3的锁,导致index3的业务只执行1s就被别人释放。
最终等于没锁的情况。
解释: 当a服务器先上锁之后,执行相关操作,此时a服务器卡顿(这里就不会手动释放锁),此时锁过期后,b服务器拿到锁,执行具体操作,然后a服务器卡顿结束,手动释放锁,这里就会把b服务器的锁给释放掉
解决方案:setnx获取锁时,设置一个指定的唯一值(例如:uuid);释放前获取这个值,判断是否自己的锁
四、优化之UUID防误删
package com.angoubiubiu.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.UUID; import java.util.concurrent.TimeUnit; @RestController public class RedisController { @Autowired private RedisTemplate redisTemplate; @GetMapping("/redis") public String testRedis() { //设置值到redis redisTemplate.opsForValue().set("name","lucy"); //从redis获取值 String name = (String)redisTemplate.opsForValue().get("name"); return name; } /** * 测试加锁情况 */ @GetMapping("testLock") public void testLock(){ String uuid= UUID.randomUUID().toString().replace("-",""); //1获取锁,setne Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,3, TimeUnit.SECONDS);//3秒之后过期 //2获取锁成功、查询num的值 if(lock){ Object value = redisTemplate.opsForValue().get("num"); //2.1判断num为空return if(StringUtils.isEmpty(value)){ return; } //2.2有值就转成成int int num = Integer.parseInt(value+""); //2.3把redis的num加1 redisTemplate.opsForValue().set("num", ++num); //如果当前uuid 和 锁里面存的uuid相同才给予释放锁 if(uuid.equals(redisTemplate.opsForValue().get(lock))){ //2.4释放锁,del redisTemplate.delete("lock"); } }else{ //3获取锁失败、每隔0.1秒再获取 try { Thread.sleep(100); testLock(); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 测试不加锁情况 */ @GetMapping("noLock") public void noLock(){ Object value = redisTemplate.opsForValue().get("num"); //2.1判断num为空return if(StringUtils.isEmpty(value)){ return; } //2.2有值就转成成int int num = Integer.parseInt(value+""); //2.3把redis的num加1 redisTemplate.opsForValue().set("num", ++num); } }
问题:删除操作缺乏原子性。
场景:
1. index1执行删除时,查询到的lock值确实和uuid相等
uuid=v1
set(lock,uuid);
2. index1执行删除前,lock刚好过期时间已到,被redis自动释放
在redis中没有了lock,没有了锁。
3. index2获取了lock
index2线程获取到了cpu的资源,开始执行方法
uuid=v2
set(lock,uuid);
4. index1执行删除,此时会把index2的lock删除
index1 因为已经在方法中了,所以不需要重新上锁。index1有执行的权限。index1已经比较完成了,这个时候,开始执行
删除的index2的锁!
解释:当a服务器上锁后,进行具体操作,对比uuid之后(对比完后)准备释放锁,此时a服务器的锁过期了,b服务器上锁后进行具体操作,由于a服务器已经对比过uuid了,此时直接释放锁,会把b服务器的锁给释放掉
五、优化之LUA脚本保证删除的原子性
package com.angoubiubiu.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Arrays; import java.util.UUID; import java.util.concurrent.TimeUnit; @RestController public class RedisController { @Autowired private RedisTemplate redisTemplate; @GetMapping("/redis") public String testRedis() { //设置值到redis redisTemplate.opsForValue().set("name","lucy"); //从redis获取值 String name = (String)redisTemplate.opsForValue().get("name"); return name; } /** * 测试加锁情况 */ @GetMapping("testLock") public void testLock(){ String uuid= UUID.randomUUID().toString().replace("-",""); //1获取锁,setne Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,3, TimeUnit.SECONDS);//3秒之后过期 //2获取锁成功、查询num的值 if(lock){ Object value = redisTemplate.opsForValue().get("num"); //2.1判断num为空return if(StringUtils.isEmpty(value)){ return; } //2.2有值就转成成int int num = Integer.parseInt(value+""); //2.3把redis的num加1 redisTemplate.opsForValue().set("num", ++num); //如果当前uuid 和 锁里面存的uuid相同才给予释放锁 if(uuid.equals(redisTemplate.opsForValue().get(lock))){ //2.4释放锁,del redisTemplate.delete("lock"); } }else{ //3获取锁失败、每隔0.1秒再获取 try { Thread.sleep(100); testLock(); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 测试不加锁情况 */ @GetMapping("noLock") public void noLock(){ Object value = redisTemplate.opsForValue().get("num"); //2.1判断num为空return if(StringUtils.isEmpty(value)){ return; } //2.2有值就转成成int int num = Integer.parseInt(value+""); //2.3把redis的num加1 redisTemplate.opsForValue().set("num", ++num); } @GetMapping("testLockLua") public void testLockLua() { //1 声明一个uuid ,将做为一个value 放入我们的key所对应的值中 String uuid = UUID.randomUUID().toString(); //2 定义一个锁:lua 脚本可以使用同一把锁,来实现删除! String skuId = "25"; // 访问skuId 为25号的商品 100008348542 String locKey = "lock:" + skuId; // 锁住的是每个商品的数据 // 3 获取锁 Boolean lock = redisTemplate.opsForValue().setIfAbsent(locKey, uuid, 3, TimeUnit.SECONDS); // 第一种: lock 与过期时间中间不写任何的代码。 // redisTemplate.expire("lock",10, TimeUnit.SECONDS);//设置过期时间 // 如果true if (lock) { // 执行的业务逻辑开始 // 获取缓存中的num 数据 Object value = redisTemplate.opsForValue().get("num"); // 如果是空直接返回 if (StringUtils.isEmpty(value)) { return; } // 不是空 如果说在这出现了异常! 那么delete 就删除失败! 也就是说锁永远存在! int num = Integer.parseInt(value + ""); // 使num 每次+1 放入缓存 redisTemplate.opsForValue().set("num", String.valueOf(++num)); /*使用lua脚本来锁*/ // 定义lua 脚本 String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; // 使用redis执行lua执行 DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(); redisScript.setScriptText(script); // 设置一下返回值类型 为Long // 因为删除判断的时候,返回的0,给其封装为数据类型。如果不封装那么默认返回String 类型, // 那么返回字符串与0 会有发生错误。 redisScript.setResultType(Long.class); // 第一个要是script 脚本 ,第二个需要判断的key,第三个就是key所对应的值。 redisTemplate.execute(redisScript, Arrays.asList(locKey), uuid); } else { // 其他线程等待 try { // 睡眠 Thread.sleep(1000); // 睡醒了之后,调用方法。 testLockLua(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
项目中正确使用:
1. 定义key,key应该是为每个sku定义的,也就是每个sku有一把锁。
String locKey ="lock:"+skuId; // 锁住的是每个商品的数据
Boolean lock = redisTemplate.opsForValue().setIfAbsent(locKey, uuid,3,TimeUnit.SECONDS);
总结
1、加锁
// 1. 从redis中获取锁,set k1 v1 px 20000 nx String uuid = UUID.randomUUID().toString(); Boolean lock = this.redisTemplate.opsForValue() .setIfAbsent("lock", uuid, 2, TimeUnit.SECONDS);
2、使用lua释放锁
// 2. 释放锁 del String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; // 设置lua脚本返回的数据类型 DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(); // 设置lua脚本返回类型为Long redisScript.setResultType(Long.class); redisScript.setScriptText(script); redisTemplate.execute(redisScript, Arrays.asList("lock"),uuid);
3、重试
Thread.sleep(500);
testLock();
为了确保分布式锁可用,我们至少要确保锁的实现同时满足以下四个条件:
- 互斥性。在任意时刻,只有一个客户端能持有锁。
- 不会发生死锁。即使有一个客户端在持有锁的期间崩溃而没有主动解锁,也能保证后续其他客户端能加锁。
- 解铃还须系铃人。加锁和解锁必须是同一个客户端,客户端自己不能把别人加的锁给解了。
- 加锁和解锁必须具有原子性。
本文作者:KwFruit
本文链接:https://www.cnblogs.com/mangoubiubiu/p/15942512.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
2021-02-27 @JsonInclude(JsonInclude.Include.NON_EMPTY) 注解无效
2021-02-27 [Vue warn]: Unknown custom element: <el-cascader> - di