|
|
package com.yohoufo.common.cache;
|
|
|
|
|
|
import com.google.common.collect.Lists;
|
|
|
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.data.redis.core.script.DefaultRedisScript;
|
|
|
import org.springframework.data.redis.core.script.RedisScript;
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
import java.util.concurrent.TimeUnit;
|
...
|
...
|
@@ -14,6 +17,8 @@ import java.util.concurrent.TimeUnit; |
|
|
@Slf4j
|
|
|
public class RedisLock {
|
|
|
|
|
|
private static final Long RELEASE_SUCCESS = 1L;
|
|
|
|
|
|
@Redis("gwNoSyncRedis")
|
|
|
private YHRedisTemplate redis;
|
|
|
|
...
|
...
|
@@ -40,15 +45,22 @@ public class RedisLock { |
|
|
try {
|
|
|
deleteKeyIfValueEquals(key, value);
|
|
|
} catch (Exception e1) {
|
|
|
log.warn("release lock {} fail", key, e);
|
|
|
log.warn("release lock fail, key is {} value is {}", key, value);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private void deleteKeyIfValueEquals(RedisKeyBuilder key, String value) {
|
|
|
String redisLockValue = valueOperations.get(key);
|
|
|
if (value.equals(redisLockValue)) {
|
|
|
redis.delete(key);
|
|
|
private boolean deleteKeyIfValueEquals(RedisKeyBuilder keyBuilder, String value) {
|
|
|
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
|
|
|
RedisScript<Long> redisScript = new DefaultRedisScript(script, Long.class);
|
|
|
String key = keyBuilder.getKey();
|
|
|
Long result = redis.getStringRedisTemplate().execute(redisScript, Lists.newArrayList(key), value);
|
|
|
if (RELEASE_SUCCESS.equals(result)) {
|
|
|
log.info("release lock ok, key is {} value is {}", key, value);
|
|
|
return true;
|
|
|
} else {
|
|
|
log.info("release lock ko, key is {} value is {}", key, value);
|
|
|
return false;
|
|
|
}
|
|
|
}
|
|
|
|
...
|
...
|
|