本地锁工具类
# 起步依赖
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.3</version>
</dependency>
1
2
3
4
5
2
3
4
5
1
2
3
4
5
2
3
4
5
# LockUtil
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* 本地锁工具类,每个key一把锁
*/
public class LockUtil {
private LockUtil() {
throw new IllegalStateException("工具类禁止实例化");
}
/**
* 线程安全,具有过期时间
*/
private static final Cache<String, ReentrantLock> LOCK_CACHE = Caffeine.newBuilder()
.expireAfterAccess(10, TimeUnit.MINUTES)
.maximumSize(1000)
.build();
/**
* 获取锁实例
* 如果key不存在则新建ReentrantLock
*
* @param key key
* @return Lock
*/
public static ReentrantLock getLock(String key) {
return LOCK_CACHE.get(key, lock->newLock());
}
/**
* 移除缓存的已解锁lock实例
*
* @param key key
*/
public static void removeCacheLock(String key) {
ReentrantLock cacheLock = LOCK_CACHE.getIfPresent(key);
if (cacheLock != null) {
LOCK_CACHE.invalidate(key);
}
}
/**
* 新建锁
*
* @return ReentrantLock
*/
private static ReentrantLock newLock(){
return new ReentrantLock();
}
}
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
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
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
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
编辑 (opens new window)
上次更新: 2023/06/07, 15:48:32
- 01
- SpringCache基本配置类05-16
- 03
- Rpamis-security-原理解析12-13