...
|
...
|
@@ -19,20 +19,24 @@ public class RedisLock { |
|
|
|
|
|
private static final Long RELEASE_SUCCESS = 1L;
|
|
|
|
|
|
private static final String ACQUIRE_SUCCESS = "OK";
|
|
|
private static final String SET_IF_NOT_EXIST = "NX";
|
|
|
private static final String SET_WITH_EXPIRE_TIME = "PX";
|
|
|
|
|
|
@Redis("gwNoSyncRedis")
|
|
|
private YHRedisTemplate redis;
|
|
|
|
|
|
@Redis("gwNoSyncRedis")
|
|
|
private YHValueOperations valueOperations;
|
|
|
|
|
|
public boolean acquire(RedisKeyBuilder key, String value, final long timeout, final TimeUnit unit) {
|
|
|
public boolean acquire(RedisKeyBuilder keyBuilder, 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;
|
|
|
String script = "return redis.call('set', KEYS[1],ARGV[1],ARGV[2],ARGV[3],ARGV[4])";
|
|
|
RedisScript<String> redisScript = new DefaultRedisScript(script, Long.class);
|
|
|
String key = keyBuilder.getKey();
|
|
|
String result = redis.getStringRedisTemplate().execute(redisScript, Lists.newArrayList(key),
|
|
|
value, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, unit.toMillis(timeout));
|
|
|
return ACQUIRE_SUCCESS.equals(result);
|
|
|
} catch (Exception e) {
|
|
|
return false;
|
|
|
}
|
...
|
...
|
|