文章目录
- 1、AlbumInfoApiController --》testLock()
- 2、AlbumInfoServiceImpl --》testLock()
- 3、问题:可能会释放其他服务器的锁。
在Redis中设置一个名为lock的键,值为111,并且只有在该键不存在时才设置(即获取锁)。同时,该键被设置了20秒的过期时间,以防止锁被永久持有。
[root@localhost ~]# docker exec -it spzx-redis redis-cli
127.0.0.1:6379> auth 123456
OK
127.0.0.1:6379> set lock 111 nx ex 20
OK
127.0.0.1:6379> get lock
"111"
127.0.0.1:6379> ttl lock
(integer) 12
127.0.0.1:6379> ttl lock
(integer) 10
127.0.0.1:6379> ttl lock
(integer) 7
127.0.0.1:6379> ttl lock
(integer) 4
127.0.0.1:6379> ttl lock
(integer) 2
127.0.0.1:6379> ttl lock
(integer) -2
127.0.0.1:6379> ttl lock
(integer) -2
127.0.0.1:6379> ttl lock
死锁问题:
redis客户端程序获取了锁之后,服务器立马宕机,就会导致死锁。
解决方案:给锁添加过期时间,时间到了自动释放锁。
设置过期时间有两种方式:
1. 首先想到通过expire设置过期时间(缺乏原子性:如果在setnx和expire之间出现异常,锁也无法释放)
2. 在set时指定过期时间(推荐)
设置过期时间:
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()
@Overridepublic void testLock(){// 加锁Boolean lock = this.redisTemplate.opsForValue().setIfAbsent("lock", "111", 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);// 解锁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 requestsServer Software:
Server Hostname: 192.168.74.1
Server Port: 8500Document Path: /api/album/albumInfo/test/lock
Document Length: 76 bytesConcurrency Level: 100
Time taken for tests: 45.796 seconds
Complete requests: 5000
Failed requests: 678(Connect: 0, Receive: 0, Length: 678, Exceptions: 0)
Write errors: 0
Total transferred: 2353390 bytes
HTML transferred: 383390 bytes
Requests per second: 109.18 [#/sec] (mean)
Time per request: 915.929 [ms] (mean)
Time per request: 9.159 [ms] (mean, across all concurrent requests)
Transfer rate: 50.18 [Kbytes/sec] receivedConnection Times (ms)min mean[+/-sd] median max
Connect: 0 1 2.2 1 31
Processing: 5 872 2799.8 13 40002
Waiting: 5 872 2799.8 13 40002
Total: 6 873 2800.2 15 40006Percentage of the requests served within a certain time (ms)50% 1566% 18775% 49880% 80990% 219195% 423398% 827899% 13608100% 40006 (longest request)
3、问题:可能会释放其他服务器的锁。
场景:如果业务逻辑的执行时间是7s。执行流程如下
-
service1业务逻辑没执行完,3秒后锁被自动释放。
-
service2获取到锁,执行业务逻辑,3秒后锁被自动释放。
-
service3获取到锁,执行业务逻辑。
-
service1业务逻辑执行完成,开始调用del释放锁,这时释放的是service3的锁,导致service3的业务只执行1s就被别人释放。
最终等于没锁的情况。
解决:setnx获取锁时,设置一个指定的唯一值(例如:uuid);释放前获取这个值,判断是否自己的锁。