import cn.hutool.core.date.DateUnit;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class RedisLock {
/** 过期时间 */
private static final long TIME_OUT = 10 * DateUnit.SECOND.getMillis();
/** 尝试间隔 */
private static final long TRY_SPACING = 100L;
/** 最大尝试次数(超过抛出稍后请重试) */
private static final long MAX_TRY_COUNT = 50;
@Resource private RedisTemplate<Object, Object> redisTemplate;
/**
* @param key 锁的键值
* @return 获得的锁的唯一标识
*/
public String tryLock(String key) {
if (StrUtil.isNotEmpty(key)) {
try {
String lockToken = UUID.fastUUID().toString();
int tryCount = 0;
while (!Objects.equals(
Boolean.TRUE,
redisTemplate
.opsForValue()
.setIfAbsent(key, lockToken, TIME_OUT, TimeUnit.MILLISECONDS))) {
if (tryCount >= MAX_TRY_COUNT) throw new Exception("---超出最大重试次数---");
tryCount++;
Thread.sleep(TRY_SPACING);
}
log.debug("---获取{}锁成功 唯一标识{}---", key, lockToken);
return lockToken;
} catch (Exception e) {
log.error(StrUtil.format("---获取{}锁失败---", key), e);
}
}
return null;
}
public void freeLock(String key, String lockToken) {
if (StrUtil.isAllNotEmpty(key, lockToken)) {
try {
String script =
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setResultType(Long.class);
redisScript.setScriptText(script);
Long res = redisTemplate.execute(redisScript, Collections.singletonList(key), lockToken);
if (Objects.equals(res, 1L)) return;
} catch (Exception e) {
log.error(StrUtil.format("---释放{}锁异常 唯一标识{}---", key, lockToken), e);
}
log.error("---释放{}锁失败 唯一标识{}---", key, lockToken);
}
}
}