分布式锁最好的实现方案是使用数据库实现分布式锁。
public boolean acquire(String lockId, long timeout) {
long futureTime = System.currentTimeMillis() + timeout;
long timeRange = 500L;
while (true) {
CountDownLatch latch = new CountDownLatch(1);
try {
DistributeLockV2 lock = new DistributeLockV2();
lock.setId(lockId);
lock.setAddTime(new Date());
lock.setServerId(this.serverId);
distributeLockMapper.insert(lock);
return true;
} catch (Exception e) {
log.error("Acquire lock failed", e);
DistributeLockV2 lock = this.distributeLockMapper.select(lockId);
if (lock == null) {
continue;
}
Date lastAddTime = lock.getAddTime();
if (System.currentTimeMillis() - lastAddTime.getTime() > (maxLockTime * 60) * 1000L) {
release(lockId, 500L);
}
try {
latch.await(timeRange, TimeUnit.MILLISECONDS);
} catch (InterruptedException interruptedException) {
log.error("Acquire lock failed", interruptedException);
}
long remain = futureTime - System.currentTimeMillis();
if (remain <= 0L) {
break;
}
if (remain < timeRange) {
timeRange = remain;
}
}
}
return false;
}
public boolean release(String lockId, long timeout) {
long futureTime = System.currentTimeMillis() + timeout;
long timeRange = 500L;
while (true) {
CountDownLatch latch = new CountDownLatch(1);
try {
distributeLockMapper.delete(lockId);
return true;
} catch (Exception e) {
log.error("Release lock failed", e);
try {
latch.await(timeRange, TimeUnit.MILLISECONDS);
} catch (InterruptedException interruptedException) {
log.error("Release lock failed", interruptedException);
}
long remain = futureTime - System.currentTimeMillis();
if (remain <= 0L) {
break;
}
if (remain < timeRange) {
timeRange = remain;
}
}
}
return false;
}