SpringBoot基于Redis的分布式锁实现过程记录
一、概述
分布式锁的重要性不言而喻,原因不在赘述,每一位菜鸟都有理由掌握它。提到分布式锁,解决方案更是乌泱乌泱的,如:
直接通过关系型数据库实现
基于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);
}
/**
* 配置redisson客户端
* @return org.redisson.Redisson
* @author zhangxs
* @date 2022-01-06 10:01
*/
@Bean
public Redisson redisson(){
// 单机模式
Config config = new Config();
config.useSingleServer().setAddress("redis://192.144.228.170:6379").setDatabase(0);
return (Redisson) Redisson.create(config);
}
}
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(){// 分布式高并发场景下,这样肯定不行
synchronized (this) {
int stock = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("stock")));
if (stock > 0) {
int currentStock = stock - 1;
redisTemplate.opsForValue().set("stock", currentStock + "");
System.out.println("扣减成功,当前库存为" + currentStock);
} else {
System.out.println("库存不足,扣减失败!");
}
}
return ResponseEntity.ok("success");
}
@GetMapping(“/minus1”)
public ResponseEntity<String> minusInventory1(){// 相当于setnx命令
String lockKey = "lockKey";
// 务必加try-finally,因为如果服务挂了,锁还得释放
String clientId = UUID.randomUUID().toString();
try {
// 相当于加锁
// Boolean absent = redisTemplate.opsForValue().setIfAbsent(lockKey, "zxs");
// 上下两行不能分开写,如果这中间报异常了,依然出现死锁
// redisTemplate.expire(lockKey,10, TimeUnit.SECONDS);
Boolean absent = redisTemplate.opsForValue().setIfAbsent(lockKey, clientId,30,TimeUnit.SECONDS);
if (!absent) {
return ResponseEntity.notFound().build();
}
int stock = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("stock")));
if (stock > 0) {
int currentStock = stock - 1;
redisTemplate.opsForValue().set("stock", currentStock + "");
System.out.println("扣减成功,当前库存为" + currentStock);
} else {
System.out.println("库存不足,扣减失败!");
}
} finally {
// 如果系统挂了呢,finally也不起作用了,因此还需要设置超时时间
// 释放锁之前,判断一下,务必释放的锁是自己持有的锁
if (clientId.equals(redisTemplate.opsForValue().get(lockKey))) {
redisTemplate.delete(lockKey);
}
}
return ResponseEntity.ok("success");
}
/**
* 终极方案
*/
@GetMapping("/minus2")
public ResponseEntity<String> minusInventory2(){
// redisson解决方案
String lockKey = "lockKey";
RLock lock = redisson.getLock(lockKey);
try {
// 加锁
lock.lock();
int stock = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("stock")));
if (stock > 0) {
int currentStock = stock - 1;
redisTemplate.opsForValue().set("stock", currentStock + "");
System.out.println("扣减成功,当前库存为" + currentStock);
} else {
System.out.println("库存不足,扣减失败!");
}
} finally {
// 释放锁
lock.unlock();
}
return ResponseEntity.ok("success");
}
}
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帮我们解决了上面的实现方式出现的尴尬情况
上一篇: 细说函数和数据类型
下一篇: 表格的使用方法及表单使用方式学习