|
@@ -195,4 +195,41 @@ public class DistributedLock {
|
|
|
unlock(lock);
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+ public <T> T runIfLockWaitGet(final String lockName, Callable<T> callable, final long timeout, TimeUnit unit) {
|
|
|
+ RLock lock = redissonClient.getLock(lockName);
|
|
|
+ if (Objects.isNull(lock)) {
|
|
|
+ log.info("callIfLockCanGet lock is null lockName : {}", lockName);
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ ExecutorService executor = Executors.newCachedThreadPool();
|
|
|
+ try {
|
|
|
+ if (lock.tryLock(timeout, timeout, unit)) {
|
|
|
+ log.info("callIfLockCanGet lock lockName : {} time is {}", lockName, System.currentTimeMillis());
|
|
|
+ Future<T> submit = executor.submit(callable);
|
|
|
+ return submit.get();
|
|
|
+ } else {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ } catch (BizException e) {
|
|
|
+ throw e;
|
|
|
+ } catch (ExecutionException e) {
|
|
|
+ Throwable cause = e.getCause();
|
|
|
+ cause.printStackTrace();
|
|
|
+ ;
|
|
|
+
|
|
|
+ String message = cause.getMessage();
|
|
|
+ if (StringUtil.isEmpty(message)) {
|
|
|
+ throw new RuntimeException("任务执行异常");
|
|
|
+ } else {
|
|
|
+ throw new BizException(message);
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("callIfLockCanGet error lockKey {}", lockName);
|
|
|
+ throw new RuntimeException("任务执行异常");
|
|
|
+ } finally {
|
|
|
+ executor.shutdown();
|
|
|
+ unlock(lock);
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|