我正在使用 Redisson
RLock lock = redissonClient().getLock(key);
try {
if (lock.tryLock()) {
// Logic here
redissonClient().getMap().get("key"); // returns value
lock.unlock();
}
redissonClient().getMap().get("key"); // returns NULL
} catch (Exception e) {
LOG.error("Error..", e);
} finally {
if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()) {
lock.unlock();
LOG.debug("lock released");
}
}
如果我不使用锁,一切都会按预期工作,但解锁后,返回的值始终为空。
RLock lock = redissonClient().getLock(key);
try {
if (lock.tryLock()) {
try {
// Logic here
Object value = redissonClient().getMap().get("key"); // returns value
// Do something with the value
} finally {
// Ensure unlock is called in a finally block to guarantee it happens
lock.unlock();
}
} else {
// Handle the case where the lock couldn't be acquired
LOG.info("Failed to acquire lock for key: {}", key);
}
// Here, after the lock is released, check if the value is still there
Object valueAfterUnlock = redissonClient().getMap().get("key");
if (valueAfterUnlock == null) {
LOG.warn("Value for key {} is null after lock release", "key");
}
} catch (Exception e) {
LOG.error("Error occurred while processing with lock", e);
} finally {
// This check is redundant here since we've already managed the lock in the try block
// but it's good practice to ensure locks are released if for some reason they weren't earlier
if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()) {
lock.unlock();
LOG.debug("Lock released manually");
}
}