@RequestMapping(value = "/testLock", method = RequestMethod.POST)
public BaseResponse<Boolean> testLock(@RequestBody TestLockRequest testLockRequest) {
String lockKey = "testLock:" + testLockRequest.getUserId();
RLock lock = redissonClient.getLock(lockKey);
boolean isLocked = false;
try {
// 尝试获取锁,等待 3 秒,如果获取到锁,则通过看门狗自动续期,直到业务完成
isLocked = lock.tryLock(3, TimeUnit.SECONDS);
if (!isLocked) {
log.warn("获取锁失败,userId: {}", testLockRequest.getUserId());
return RspUtils.error("操作繁忙,请稍后再试!");
}
log.info("获取锁成功,使用看门狗动态续期,userId: {}", testLockRequest.getUserId());
// TODO: 执行业务逻辑
// doBusinessLogic(testLockRequest);
return RspUtils.success();
} catch (Exception e) {
log.error("业务执行异常,userId: {}", testLockRequest.getUserId(), e);
return RspUtils.error("操作失败");
} finally {
// 确保锁释放
if (isLocked && lock.isHeldByCurrentThread()) {
lock.unlock();
log.info("释放锁成功,userId: {}", testLockRequest.getUserId());
}
}
}
@RequestMapping(value = "/testLock", method = RequestMethod.POST)
public BaseResponse<Boolean> testLock(@RequestBody TestLockRequest testLockRequest) {
String lockKey = "testLock:" + testLockRequest.getUserId();
RLock lock = redissonClient.getLock(lockKey);
try {
// 阻塞等待获取锁
lock.lock();
log.info("获取锁成功,userId: {}", testLockRequest.getUserId());
// TODO: 执行业务逻辑
// doBusinessLogic(testLockRequest);
return RspUtils.success();
} catch (Exception e) {
log.error("业务执行异常,userId: {}", testLockRequest.getUserId(), e);
return RspUtils.error("操作失败");
} finally {
// 安全释放锁
if (lock.isHeldByCurrentThread()) {
lock.unlock();
log.info("释放锁成功,userId: {}", testLockRequest.getUserId());
}
}
}