-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedisReentrancyThreadLocalLock.java
More file actions
96 lines (82 loc) · 2.6 KB
/
RedisReentrancyThreadLocalLock.java
File metadata and controls
96 lines (82 loc) · 2.6 KB
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
package com.example.lock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 基于 ThreadLocal 内存可重入分布式锁<br>
* 分布式锁详情参考:<br>
* SimpleRedisLock
*
* @author andyXu xu9529@gmail.com
* @date 2020/6/13
*/
@Service
public class RedisReentrancyThreadLocalLock {
private static ThreadLocal<Map<String, Integer>> LOCKS = ThreadLocal.withInitial(HashMap::new);
@Autowired
SimpleRedisLock redisLock;
/**
* 可重入锁
*
* @param lockName 锁名字,代表需要争临界资源
* @param request 唯一标识,可以使用 uuid,根据该值判断是否可以重入
* @param leaseTime 锁释放时间
* @param unit 锁释放时间单位
* @return
*/
public Boolean tryLock(String lockName, String request, long leaseTime, TimeUnit unit) {
Map<String, Integer> counts = LOCKS.get();
if (counts.containsKey(lockName)) {
counts.put(lockName, counts.get(lockName) + 1);
return true;
} else {
if (redisLock.tryLock(lockName, request, leaseTime, unit)) {
counts.put(lockName, 1);
return true;
}
}
return false;
}
/**
* 解锁需要判断不同线程池
*
* @param lockName
* @param request
*/
public void unlock(String lockName, String request) {
Map<String, Integer> counts = LOCKS.get();
if (counts.getOrDefault(lockName, 0) <= 1) {
counts.remove(lockName);
Boolean result = redisLock.unlock(lockName, request);
if (!result) {
throw new IllegalMonitorStateException("attempt to unlock lock, not locked by lockName:+" + lockName + " with request: "
+ request);
}
} else {
counts.put(lockName, counts.get(lockName) - 1);
}
}
/**
* 查看是否加锁
*
* @param lockName
* @return
*/
public Boolean isLocked(String lockName) {
Map<String, Integer> counts = LOCKS.get();
return (counts.getOrDefault(lockName, 0) >= 1);
}
/**
* 强制解锁
*
* @param lockName
* @return true:解锁成功,false:锁不存在,或者锁已经超时,
*/
public Boolean forceUnlock(String lockName) {
Map<String, Integer> counts = LOCKS.get();
counts.remove(lockName);
return redisLock.forceUnlock(lockName);
}
}