public class RedisDistributedLock {
private static final String LOCK_SUCCESS = "OK";
private static final Long RELEASE_SUCCESS = 1L;
private static int WAIT_TIME = 1 * 1000;
private static String EVAL_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
public String lock(Jedis jedis, String key) {
try {
// 超过等待时间,加锁失败
long waitEnd = System.currentTimeMillis() + WAIT_TIME;
String value = UUID.randomUUID().toString();
while (System.currentTimeMillis() < waitEnd) {
String result = jedis.set(key, value, "NX", "PX", 1000);
if (LOCK_SUCCESS.equals(result)) {
return value;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} catch (Exception ex) {
log.error("lock error", ex);
}
return null;
}
//key分布式锁的key value加锁时候那个UUID
public boolean release(Jedis jedis,String key,String value) {
if (value == null) {
return false;
}
return RELEASE_SUCCESS.equals(JedisUtils.eval(evalscript,Collections.singletonList(key), Collections.singletonList(value)));
}
}
来源:CSDN
作者:Hefei19881002
链接:https://blog.csdn.net/qq_23292875/article/details/104038763