分布式锁之 防误删(优化之UUID防误删)


在这里插入图片描述
实现如下:
在这里插入图片描述

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、问题:删除操作缺乏原子性。

场景:

  1. service1执行删除时,查询到的lock值确实和uuid相等
  2. service1执行删除前,lock刚好过期时间已到,被redis自动释放
  3. service2获取了lock
  4. service1执行删除,此时会把service2的lock删除
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值