修改多节点同时执行任务情况

This commit is contained in:
sh
2026-04-02 17:46:02 +08:00
parent 10a28b1b0b
commit c2b62fac6d
3 changed files with 46 additions and 5 deletions

View File

@@ -28,6 +28,7 @@ public class DistributedLockUtil {
private static final long DEFAULT_EXPIRE_SECONDS = 30;
private static final long DEFAULT_ACQUIRE_TIMEOUT_SECONDS = 5;
private static final long RENEW_INTERVAL_SECONDS = DEFAULT_EXPIRE_SECONDS / 3;
private static final long DEFAULT_EXPIRE_SECONDS_15 = 900;
// 续期线程池
private final ScheduledExecutorService renewExecutor = Executors.newScheduledThreadPool(
@@ -267,4 +268,41 @@ public class DistributedLockUtil {
// 使用默认的锁过期时间30秒也可根据需要改为让调用方传入
return acquireLockWithRenewal(lockKey, DEFAULT_EXPIRE_SECONDS, acquireTimeoutSeconds);
}
/**
* 设置15min
* @param lockKey
* @param timeout
* @param unit
* @return
*/
public String acquireLockWith15Timeout(String lockKey, long timeout, TimeUnit unit) {
// 转换超时时间为秒(向上取整避免精度丢失)
long acquireTimeoutSeconds = (long) Math.ceil((double) unit.toMillis(timeout) / 1000);
// 使用默认的锁过期时间30秒也可根据需要改为让调用方传入
return acquireLockWithRenewal(lockKey, DEFAULT_EXPIRE_SECONDS_15, acquireTimeoutSeconds);
}
/**
* 定时任务
* @param lockKey
* @param timeout
* @param unit
* @return
*/
public AutoReleaseLock tryLockJob(String lockKey, long timeout, TimeUnit unit) {
if (lockKey == null || lockKey.trim().isEmpty()) {
throw new IllegalArgumentException("锁key不能为空");
}
if (timeout < 0) {
throw new IllegalArgumentException("超时时间不能为负数");
}
if (unit == null) {
throw new IllegalArgumentException("时间单位不能为空");
}
String identifier = acquireLockWith15Timeout(lockKey, timeout, unit);
return new AutoReleaseLock(this, lockKey, identifier);
}
}