分布式锁之 防误删(优化之UUID防误删)
文章目录
- 1、AlbumInfoApiController --》testLock()
- 2、AlbumInfoServiceImpl --》testLock()
- 3、问题:删除操作缺乏原子性。
实现如下:
1、AlbumInfoApiController --》testLock()
@Tag(name = "专辑管理")
@RestController
@RequestMapping("api/album/albumInfo")
@SuppressWarnings({"unchecked", "rawtypes"})
public class AlbumInfoApiController {
@GetMapping("test/lock")
public Result testLock() {
this.albumInfoService.testLock();
return Result.ok("测试分布式锁案例");
}
}
2、AlbumInfoServiceImpl --》testLock()
@Override
public void testLock(){
// 加锁:set k v nx ex 3
String uuid = UUID.randomUUID().toString();
Boolean lock = this.redisTemplate.opsForValue().setIfAbsent("lock", uuid, 3, TimeUnit.SECONDS);
if (!lock) {
try {
// 获取锁失败,进行自旋
Thread.sleep(50);
this.testLock();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}else {
// 获取锁成功,执行业务
//this.redisTemplate.expire("lock", 3, TimeUnit.SECONDS);
Object numObj = this.redisTemplate.opsForValue().get("num");
if (numObj == null) {
this.redisTemplate.opsForValue().set("num", 1);
return;
}
Integer num = Integer.parseInt(numObj.toString());
this.redisTemplate.opsForValue().set("num", ++num);
// 解锁
// 先判断是否是自己的锁,如果是则删除
if (StringUtils.equals(uuid, this.redisTemplate.opsForValue().get("lock").toString())) {
this.redisTemplate.delete("lock");
}
}
}
压力测试肯定也没有问题。自行测试
启动多个运行实例:
redis中的值重新改为0。
[root@localhost ~]# ab -n 5000 -c 100 http://192.168.74.1:8500/api/album/albumInfo/test/lock
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking 192.168.74.1 (be patient)
Completed 500 requests
Completed 1000 requests
Completed 1500 requests
Completed 2000 requests
Completed 2500 requests
Completed 3000 requests
Completed 3500 requests
Completed 4000 requests
Completed 4500 requests
Completed 5000 requests
Finished 5000 requests
Server Software:
Server Hostname: 192.168.74.1
Server Port: 8500
Document Path: /api/album/albumInfo/test/lock
Document Length: 76 bytes
Concurrency Level: 100
Time taken for tests: 56.438 seconds
Complete requests: 5000
Failed requests: 663
(Connect: 0, Receive: 0, Length: 663, Exceptions: 0)
Write errors: 0
Total transferred: 2353315 bytes
HTML transferred: 383315 bytes
Requests per second: 88.59 [#/sec] (mean)
Time per request: 1128.766 [ms] (mean)
Time per request: 11.288 [ms] (mean, across all concurrent requests)
Transfer rate: 40.72 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 2 2.5 1 23
Processing: 6 1078 3263.0 17 55303
Waiting: 6 1078 3263.0 17 55303
Total: 6 1079 3263.5 19 55319
Percentage of the requests served within a certain time (ms)
50% 19
66% 317
75% 798
80% 1210
90% 2775
95% 4876
98% 10191
99% 15899
100% 55319 (longest request)
3、问题:删除操作缺乏原子性。
场景:
- service1执行删除时,查询到的lock值确实和uuid相等
- service1执行删除前,lock刚好过期时间已到,被redis自动释放
- service2获取了lock
- service1执行删除,此时会把service2的lock删除