并发场景下分布式锁未生效
背景: 接手他人的业务后,生产发现同一个商户入网了两次,明明有分布式锁,但未生效
原因:未对tryLock判断,获取锁失败也能执行业务逻辑
经验值: 不要想的太复杂,先review代码
修改前tryLock
String lockKey = "custIncr:"+customerBean.getCustomerNo();
RLock lock = redissonClient.getLock(lockKey);
boolean tryLock = false;
try {
tryLock = lock.tryLock(0L, 30L, TimeUnit.SECONDS);
//业务逻辑
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
throw new ServerException("缓存异常,请稍后重试!" );
}catch (Exception e) {
logger.error(e.getMessage());
throw e;
}finally {
if (tryLock ) {
lock.unlock();
}
}
修改后
String lockKey = "custIncr:"+customerBean.getCustomerNo();
RLock lock = redissonClient.getLock(lockKey);
boolean tryLock = false;
try {
tryLock = lock.tryLock(0L, 30L, TimeUnit.SECONDS);
if(tryLock){
//业务逻辑
}else{
// 未能获取到锁,可以选择等待、重试或执行其他逻辑
}
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
throw new ServerException("缓存异常,请稍后重试!" );
}catch (Exception e) {
logger.error(e.getMessage());
throw e;
}finally {
if (tryLock ) {
lock.unlock();
}
}