Skip to content

Commit f813064

Browse files
committed
分布式锁优化
1 parent 36c5060 commit f813064

File tree

1 file changed

+12
-5
lines changed
  • spring-boot-student-data-redis-distributed-lock/src/main/java/com/xiaolyuh/redis/lock

1 file changed

+12
-5
lines changed

spring-boot-student-data-redis-distributed-lock/src/main/java/com/xiaolyuh/redis/lock/RedisLock3.java

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -241,9 +241,8 @@ public Boolean unlock() {
241241
// 只有加锁成功并且锁还有效才去释放锁
242242
// 只有加锁成功并且锁还有效才去释放锁
243243
if (locked) {
244-
return redisTemplate.execute(new RedisCallback<Boolean>() {
245-
@Override
246-
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
244+
try {
245+
return redisTemplate.execute((RedisConnection connection) -> {
247246
Object nativeConnection = connection.getNativeConnection();
248247
Long result = 0L;
249248

@@ -263,13 +262,21 @@ public Boolean doInRedis(RedisConnection connection) throws DataAccessException
263262
}
264263

265264
if (result == 0 && !StringUtils.isEmpty(lockKeyLog)) {
266-
logger.info("Redis分布式锁,解锁{}失败!解锁时间:{}", lockKeyLog, System.currentTimeMillis());
265+
logger.debug("Redis分布式锁,解锁{}失败!解锁时间:{}", lockKeyLog, System.currentTimeMillis());
267266
}
268267

269268
locked = result == 0;
270269
return result == 1;
270+
});
271+
} catch (Throwable e) {
272+
logger.warn(e.getMessage(), e);
273+
String value = (String) redisTemplate.opsForValue().get(lockKey);
274+
if (lockValue.equals(value)) {
275+
redisTemplate.delete(lockKey);
276+
return true;
271277
}
272-
});
278+
return false;
279+
}
273280
}
274281

275282
return true;

0 commit comments

Comments
 (0)