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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
|
package kd.bos.dlock.redis;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Supplier;
import kd.bos.dlock.AbstractDLock;
import kd.bos.dlock.DLock;
import kd.bos.dlock.DLockInfo;
import kd.bos.dlock.DLockUtil;
import kd.bos.instance.Instance;
import kd.bos.redis.JedisClient;
import kd.bos.util.DisCardUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RedisLocker extends AbstractDLock implements DLock, Comparable<RedisLocker> {
private static final Logger log = LoggerFactory.getLogger(RedisLocker.class);
private static final String ACQUIRED_INSTANCE = Instance.getInstanceId();
static final long defaultExpireTime = 300000L;
private static final String FIELD_DESC = "desc";
private static final String FIELD_OWNER = "owner";
private static final String FIELD_WAITING_LOCKS = "waitingLocks";
private static final String FIELD_CREATE_TIME = "createTime";
private static final String LOCK_SET_SCRIPT = "redis.call('pexpire', KEYS[1], ARGV[1]); redis.call('hset', KEYS[1], 'desc', ARGV[2]); redis.call('hset', KEYS[1], 'createTime', ARGV[3]); redis.call('hset', KEYS[1], 'owner', ARGV[4]); local waitLock = tonumber(redis.call('hget', KEYS[1] ,'waitingLocks')); if waitLock ~= nil and waitLock > 0 then redis.call('hincrBy', KEYS[1], 'waitingLocks', -1); end;";
private static final String UNLOCK_SCRIPT = "local waitingLocks=tonumber(redis.call('hget', KEYS[1] ,'waitingLocks')); local field = ARGV[1];local threadId=redis.call('hget', KEYS[1], 'owner');if threadId~=nil and threadId==field then if waitingLocks==nil or waitingLocks<= 0 then redis.call('del', KEYS[1]) else redis.call('hdel', KEYS[1], 'desc') end;end;";
private static final String FORCE_UNLOCK_SCRIPT = "local waitingLocks=tonumber(redis.call('hget', KEYS[1] ,'waitingLocks')); if waitingLocks==nil or waitingLocks<= 0 then redis.call('del', KEYS[1]) else redis.call('hdel', KEYS[1], 'desc') end";
private static final String RELEASE_NOT_LIVE_SCRIPT = "local field = ARGV[1];local instanceId = redis.call('hget', KEYS[1], KEYS[2]); if instanceId ~= nil and instanceId ~= ' ' then local index = string.find(instanceId, '#');instanceId = index and string.sub(instanceId, 1, index -1) or instanceId;if instanceId==field then redis.call('HDEL', KEYS[1], KEYS[2]); local waitLock = tonumber(redis.call('hget', KEYS[1] ,'waitingLocks'));if waitLock ~= nil and waitLock > 0 then redis.call('hincrBy', KEYS[1], 'waitingLocks', -1);end;end;end;";
private static final String WAITING_LOCKS_WAITING_DECR = "local waitLock = tonumber(redis.call('hget', KEYS[1] ,'waitingLocks'));if waitLock ~= nil and waitLock > 0 then redis.call('hincrBy', KEYS[1], 'waitingLocks', -1);end;";
private static final long MIN_EXPIRE_TIME = 30000L;
private static final long MAX_RETRY_INTERVAL = 1000L;
private static final ThreadLocal<SimpleDateFormat> TH_SDF = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
private long expireTime;
private Supplier<JedisClient> jedisCreator;
private Supplier<JedisClient> keeperAloneJedis;
private String lockKey;
private String lockDesc;
private static String now() {
return ((SimpleDateFormat)TH_SDF.get()).format(new Date());
}
private volatile boolean acquired = false;
private final Object unlockObj = new Object();
private RedisLockManager.ReentrantDLock rd;
private final String rootPath;
public RedisLocker(Supplier<JedisClient> jedisCreator, Supplier<JedisClient> keeperAloneJedis, String lockKey, String lockDesc, String keyPrefix) {
this(jedisCreator, keeperAloneJedis, lockKey, lockDesc, keyPrefix, 300000L);
}
public RedisLocker(Supplier<JedisClient> jedisCreator, Supplier<JedisClient> keeperAloneJedis, String lockKey, String lockDesc, String keyPrefix, long expireTime) {
if (expireTime < 30000L)
expireTime = 30000L;
Objects.requireNonNull(lockKey, "Lock key can not be null.");
this.jedisCreator = jedisCreator;
this.keeperAloneJedis = keeperAloneJedis;
this.rootPath = keyPrefix;
this.lockKey = DLockUtil.getFullPath(keyPrefix, lockKey);
this.lockDesc = ACQUIRED_INSTANCE + '#' + DLockUtil.getHostAddress() + '#' + Thread.currentThread() + '#' + ((lockDesc == null) ? "" : lockDesc);
this.expireTime = expireTime;
}
public String[] getLockAccountIds() {
try (JedisClient jedis = (JedisClient)this.jedisCreator.get()) {
Set<String> accountIds = jedis.keys(this.rootPath + "*");
if (accountIds.isEmpty())
return empty_strings;
Set<String> ret = new TreeSet<>();
for (String key : accountIds) {
key = key.substring(this.rootPath.length());
int i = key.indexOf('/');
if (i != -1)
ret.add(key.substring(0, i));
}
if (ret.isEmpty())
return empty_strings;
return ret.<String>toArray(new String[ret.size()]);
}
}
public void setReentrantDLock(RedisLockManager.ReentrantDLock rd) {
this.rd = rd;
}
boolean touchExpire() {
try (JedisClient jedis = (JedisClient)this.keeperAloneJedis.get()) {
return (1L == jedis.pexpire(this.lockKey, this.expireTime).longValue());
}
}
long pttl() {
try (JedisClient jedis = (JedisClient)this.jedisCreator.get()) {
return jedis.pttl(this.lockKey).longValue();
}
}
long getExpireTime() {
return this.expireTime;
}
public void lock() {
tryLock(Long.MAX_VALUE);
}
public boolean tryLock() {
return tryLock(1L);
}
public boolean tryLock(long msTimeout) {
boolean reentry = false;
if (this.rd != null) {
reentry = true;
if (this.rd.canRelease()) {
this.rd.incRef();
} else {
this.rd.incRef();
return true;
}
}
if (this.acquired)
throw new IllegalStateException("Has acquired");
log.info("acquire lock " + this.lockKey + "..." + (reentry ? " reentryDLock" : ""));
JedisClient jedis = this.jedisCreator.get();
try {
jedis.hincrBy(this.lockKey, "waitingLocks", 1L);
long sleep = Math.min(msTimeout, 1000L);
long ts = System.currentTimeMillis();
while (jedis.hsetnx(this.lockKey, "desc", ACQUIRED_INSTANCE).longValue() != 1L) {
String instanceId = jedis.hget(this.lockKey, "desc");
if (instanceId != null) {
int i = instanceId.indexOf('#');
if (i != -1)
instanceId = instanceId.substring(0, i);
if (!ACQUIRED_INSTANCE.equals(instanceId)) {
log.info(String.format("check lock %s instance %s if alive before...", new Object[] { this.lockKey, instanceId }));
if (!DLockUtil.isInstanceAlive(instanceId)) {
log.info(String.format("del lock %s during instance %s dead...", new Object[] { this.lockKey, instanceId }));
jedis.eval("local field = ARGV[1];local instanceId = redis.call('hget', KEYS[1], KEYS[2]); if instanceId ~= nil and instanceId ~= ' ' then local index = string.find(instanceId, '#');instanceId = index and string.sub(instanceId, 1, index -1) or instanceId;if instanceId==field then redis.call('HDEL', KEYS[1], KEYS[2]); local waitLock = tonumber(redis.call('hget', KEYS[1] ,'waitingLocks'));if waitLock ~= nil and waitLock > 0 then redis.call('hincrBy', KEYS[1], 'waitingLocks', -1);end;end;end;", 2, new String[] { this.lockKey, "desc", instanceId });
continue;
}
log.info(String.format("check lock %s instance %s still alive...", new Object[] { this.lockKey, instanceId }));
}
}
if (sleep > 0L)
try {
jedis.close();
Thread.sleep(sleep);
jedis = this.jedisCreator.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (System.currentTimeMillis() - ts >= msTimeout) {
jedis.eval("local waitLock = tonumber(redis.call('hget', KEYS[1] ,'waitingLocks'));if waitLock ~= nil and waitLock > 0 then redis.call('hincrBy', KEYS[1], 'waitingLocks', -1);end;", 1, new String[] { this.lockKey });
return false;
}
}
this.acquired = true;
jedis.eval("redis.call('pexpire', KEYS[1], ARGV[1]); redis.call('hset', KEYS[1], 'desc', ARGV[2]); redis.call('hset', KEYS[1], 'createTime', ARGV[3]); redis.call('hset', KEYS[1], 'owner', ARGV[4]); local waitLock = tonumber(redis.call('hget', KEYS[1] ,'waitingLocks')); if waitLock ~= nil and waitLock > 0 then redis.call('hincrBy', KEYS[1], 'waitingLocks', -1); end;", 1, new String[] { this.lockKey, String.valueOf(this.expireTime), this.lockDesc, now(),
String.valueOf(Thread.currentThread().getId()) });
log.info("acquired lock " + this.lockKey + (reentry ? " reentryDLock" : ""));
} catch (Exception e) {
log.info("acquire lock failed " + this.lockKey + (reentry ? " reentryDLock" : ""));
throw e;
} finally {
if (jedis != null)
jedis.close();
}
RedisLockKeeper.keep(this);
return true;
}
public void unlock() {
if (!this.acquired)
return;
log.info("release lock " + this.lockKey + "...");
if (this.rd != null) {
this.rd.decRef();
if (!this.rd.canRelease())
return;
this.rd.release(this.lockKey);
}
if (this.acquired)
synchronized (this.unlockObj) {
try (JedisClient jedis = (JedisClient)this.jedisCreator.get()) {
if (this.acquired) {
this.acquired = false;
jedis.eval("local waitingLocks=tonumber(redis.call('hget', KEYS[1] ,'waitingLocks')); local field = ARGV[1];local threadId=redis.call('hget', KEYS[1], 'owner');if threadId~=nil and threadId==field then if waitingLocks==nil or waitingLocks<= 0 then redis.call('del', KEYS[1]) else redis.call('hdel', KEYS[1], 'desc') end;end;", 1, new String[] { this.lockKey, String.valueOf(Thread.currentThread().getId()) });
RedisLockKeeper.unkeep(this);
}
} catch (Exception e) {
log.info("release lock failed " + this.lockKey + "...");
throw e;
}
}
}
public void close() {
unlock();
}
public DLock fastMode() {
return this;
}
public DLock stableMode() {
return this;
}
public int compareTo(RedisLocker o) {
return this.lockKey.compareTo(o.lockKey);
}
static DLockInfo getLockInfo(JedisClient jedis, String lockKey, String keyPrefix) {
String fullLockKey = DLockUtil.getFullPath(keyPrefix, lockKey);
Map<String, String> map = jedis.hgetAll(fullLockKey);
if (!map.isEmpty()) {
String createTime = map.get("createTime");
String desc = map.get("desc");
String owner = map.get("owner");
String waitingLocks = map.get("waitingLocks");
long n_owner = (owner == null) ? 0L : Long.parseLong(owner);
long n_createTime = 0L;
try {
n_createTime = (createTime == null) ? 0L : ((SimpleDateFormat)TH_SDF.get()).parse(createTime).getTime();
} catch (ParseException e) {
DisCardUtil.discard();
}
int n_waitingLocks = (waitingLocks == null) ? 0 : Integer.parseInt(waitingLocks);
long pttl = jedis.pttl(fullLockKey).longValue();
return new DLockInfo(lockKey, fullLockKey, desc, n_owner, n_createTime, pttl, n_waitingLocks);
}
return null;
}
static Map<String, DLockInfo> getAllLockInfo(JedisClient jedis, String keyPrefix) {
String prefix = DLockUtil.getPathPrefix(keyPrefix);
int len = prefix.length();
Map<String, DLockInfo> map = new HashMap<>();
for (String fullLockKey : jedis.keys(prefix + "*")) {
String lockKey = fullLockKey.substring(len);
DLockInfo lock = getLockInfo(jedis, lockKey, keyPrefix);
if (lock != null)
map.put(lockKey, lock);
}
return map;
}
static void forceUnlock(JedisClient jedis, String rootPath, String... keys) {
for (String key : keys) {
String fullLockKey = DLockUtil.getFullPath(rootPath, key);
log.info("unlock path :" + fullLockKey);
jedis.eval("local waitingLocks=tonumber(redis.call('hget', KEYS[1] ,'waitingLocks')); if waitingLocks==nil or waitingLocks<= 0 then redis.call('del', KEYS[1]) else redis.call('hdel', KEYS[1], 'desc') end", 1, new String[] { fullLockKey });
}
}
static void forceClear(JedisClient jedis, String rootPath, String... keys) {
for (String key : keys) {
log.info("clear lock path :" + keys);
forceUnlock(jedis, rootPath, new String[] { key });
while (getLockInfo(jedis, key, rootPath) != null) {
forceUnlock(jedis, rootPath, new String[] { key });
}
}
}
}
|