RedisLock.java
1.64 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
package com.yohoufo.common.cache;
import com.yoho.core.redis.cluster.annotation.Redis;
import com.yoho.core.redis.cluster.operations.nosync.YHRedisTemplate;
import com.yoho.core.redis.cluster.operations.nosync.YHValueOperations;
import com.yoho.core.redis.cluster.operations.serializer.RedisKeyBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class RedisLock {
@Redis("gwNoSyncRedis")
private YHRedisTemplate redis;
@Redis("gwNoSyncRedis")
private YHValueOperations valueOperations;
public boolean acquire(RedisKeyBuilder key, String value, final long timeout, final TimeUnit unit) {
try {
String redisLockValue = valueOperations.get(key);
if (StringUtils.isNoneBlank(redisLockValue)) {
return false;
}
valueOperations.set(key, value, timeout, unit);
return true;
} catch (Exception e) {
return false;
}
}
public void release(RedisKeyBuilder key, String value) {
try {
deleteKeyIfValueEquals(key, value);
} catch (Exception e) {
try {
deleteKeyIfValueEquals(key, value);
} catch (Exception e1) {
log.warn("release lock {} fail", key, e);
}
}
}
private void deleteKeyIfValueEquals(RedisKeyBuilder key, String value) {
String redisLockValue = valueOperations.get(key);
if (value.equals(redisLockValue)) {
redis.delete(key);
}
}
}