欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot基于Redis的分布式锁实现过程记录

程序员文章站 2022-05-21 23:24:15
...

一、概述
分布式锁的重要性不言而喻,原因不在赘述,每一位菜鸟都有理由掌握它。提到分布式锁,解决方案更是乌泱乌泱的,如:

直接通过关系型数据库实现
基于Redission实现
基于Apache Curator实现

本文暂时先介绍一种,基于Redission实现的方式

二、环境搭建
有一个简单的SpringBoot环境即可,便于测试:

依赖

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.6.5</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
配置
server:
port: 7077

spring:
redis:
host: 192.144.228.170
database: 0
1
2
3
4
5
6
7
启动及配置类
package com.ideax.distributed;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

Java技术迷

@SpringBootApplication
public class DistributedApplication {
public static void main(String[] args) {
SpringApplication.run(DistributedApplication.class,args);
}

  1. /**
  2. * 配置redisson客户端
  3. * @return org.redisson.Redisson
  4. * @author zhangxs
  5. * @date 2022-01-06 10:01
  6. */
  7. @Bean
  8. public Redisson redisson(){
  9. // 单机模式
  10. Config config = new Config();
  11. config.useSingleServer().setAddress("redis://192.144.228.170:6379").setDatabase(0);
  12. return (Redisson) Redisson.create(config);
  13. }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
三、模拟一个库存扣减的场景
package com.ideax.distributed.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**

  • 库存 前端控制器
  • @author zhangxs
  • @date 2022-01-06 09:46
    */
    @RequestMapping(“/inventory”)
    @RestController
    public class InventoryController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private Redisson redisson;

    @GetMapping(“/minus”)
    public ResponseEntity<String> minusInventory(){

    1. // 分布式高并发场景下,这样肯定不行
    2. synchronized (this) {
    3. int stock = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("stock")));
    4. if (stock > 0) {
    5. int currentStock = stock - 1;
    6. redisTemplate.opsForValue().set("stock", currentStock + "");
    7. System.out.println("扣减成功,当前库存为" + currentStock);
    8. } else {
    9. System.out.println("库存不足,扣减失败!");
    10. }
    11. }
    12. return ResponseEntity.ok("success");

    }

    @GetMapping(“/minus1”)
    public ResponseEntity<String> minusInventory1(){

    1. // 相当于setnx命令
    2. String lockKey = "lockKey";
    3. // 务必加try-finally,因为如果服务挂了,锁还得释放
    4. String clientId = UUID.randomUUID().toString();
    5. try {
    6. // 相当于加锁
    7. // Boolean absent = redisTemplate.opsForValue().setIfAbsent(lockKey, "zxs");
    8. // 上下两行不能分开写,如果这中间报异常了,依然出现死锁
    9. // redisTemplate.expire(lockKey,10, TimeUnit.SECONDS);
    10. Boolean absent = redisTemplate.opsForValue().setIfAbsent(lockKey, clientId,30,TimeUnit.SECONDS);
    11. if (!absent) {
    12. return ResponseEntity.notFound().build();
    13. }
  1. int stock = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("stock")));
  2. if (stock > 0) {
  3. int currentStock = stock - 1;
  4. redisTemplate.opsForValue().set("stock", currentStock + "");
  5. System.out.println("扣减成功,当前库存为" + currentStock);
  6. } else {
  7. System.out.println("库存不足,扣减失败!");
  8. }
  9. } finally {
  10. // 如果系统挂了呢,finally也不起作用了,因此还需要设置超时时间
  11. // 释放锁之前,判断一下,务必释放的锁是自己持有的锁
  12. if (clientId.equals(redisTemplate.opsForValue().get(lockKey))) {
  13. redisTemplate.delete(lockKey);
  14. }
  15. }
  16. return ResponseEntity.ok("success");
  17. }
  18. /**
  19. * 终极方案
  20. */
  21. @GetMapping("/minus2")
  22. public ResponseEntity<String> minusInventory2(){
  23. // redisson解决方案
  24. String lockKey = "lockKey";
  25. RLock lock = redisson.getLock(lockKey);
  26. try {
  27. // 加锁
  28. lock.lock();
  29. int stock = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("stock")));
  30. if (stock > 0) {
  31. int currentStock = stock - 1;
  32. redisTemplate.opsForValue().set("stock", currentStock + "");
  33. System.out.println("扣减成功,当前库存为" + currentStock);
  34. } else {
  35. System.out.println("库存不足,扣减失败!");
  36. }
  37. } finally {
  38. // 释放锁
  39. lock.unlock();
  40. }
  41. return ResponseEntity.ok("success");
  42. }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
四、总结
@GetMapping(“/minus”) public ResponseEntity<String> minusInventory():初步实现方式,在单线程环境下可以使用,但是在分布式高并发场景下,毫无疑问是肯定不行的
@GetMapping(“/minus1”) public ResponseEntity<String> minusInventory1():进阶实现方式,在一般的不拘小节的公司,勉强够用,但是你需要考虑一下,锁过期时间,到底设置多少才能完美呢?
@GetMapping(“/minus2”) public ResponseEntity<String> minusInventory2():终极实现方式,redisson帮我们解决了上面的实现方式出现的尴尬情况