直接贴代码
String instanceId = "123456789";
String dmlType = INSERT.getType();
String corpId = "324234";
RLock lock = redissonClient.getLock(ProcessingConstant.SYNC_INCR_FORM_DATA_PREFIX_KEY + instanceId + UNDERLINE + dmlType);
try {
// 尝试获取, 获取
boolean isLock = lock.tryLock(10, 5, TimeUnit.MINUTES);
//boolean isLock = lock.tryLock(10, TimeUnit.SECONDS);
Thread.sleep(2000);
if (!isLock) {
log.warn("正在同步中,请等待同步完成 corpId = {}, instanceId is {}", corpId, instanceId);
return;
}
} catch (InterruptedException e) {
// 此处无需抛异常,因为有两个在监听
log.warn("正在同步,获取锁失败!corpId:{} , errorMsg:{}", corpId, e.getMessage(), e);
} catch (Exception e) {
log.error("handleIncrInstanceData 数据同步失败!corpId:{} , errorMsg:{}", corpId, e.getMessage(), e);
if (lock.isLocked() && lock.isHeldByCurrentThread() && INSERT.getType().equals(dmlType)) {
lock.unlock();
}
throw e;
} finally {
if (lock.isLocked() && lock.isHeldByCurrentThread()) {
// 新增类型时等其自己过期,5分钟,规避网络重发的问题
if (!DMLTypeEnum.INSERT.getType().equals(dmlType)) {
lock.unlock();
}
}
}
很明显这里尝试获取锁,如果如果获取不到就等待10分钟
// 尝试获取, 获取
boolean isLock = lock.tryLock(10, 5, TimeUnit.MINUTES);
而业务其实是要求获取锁不到直接走此处
if (!isLock) {
log.warn("正在同步中,请等待同步完成 corpId = {}, instanceId is {}", corpId, instanceId);
return;
}
需把waitTime改为0
// 尝试获取, 获取
boolean isLock = lock.tryLock(0, 5, TimeUnit.MINUTES);
总结:
对于不熟悉的方法必须要走单元测试,做程序要具有严谨的态度