Skip to content

Commit be19f1c

Browse files
committed
分布式锁优化
1 parent d9905db commit be19f1c

File tree

2 files changed

+29
-8
lines changed
  • spring-boot-student-data-redis-distributed-lock/src/main/java/com/xiaolyuh/redis/lock
  • spring-boot-student-layering-cache

2 files changed

+29
-8
lines changed

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

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -269,8 +269,8 @@ public Boolean unlock() {
269269
return result == 1;
270270
});
271271
} catch (Throwable e) {
272-
logger.warn("Redis不支持EVAL命令,使用降级方式解锁:{}",e.getMessage(), e);
273-
String value = (String) redisTemplate.opsForValue().get(lockKey);
272+
logger.warn("Redis不支持EVAL命令,使用降级方式解锁:{}", e.getMessage());
273+
String value = this.get(lockKey, String.class);
274274
if (lockValue.equals(value)) {
275275
redisTemplate.delete(lockKey);
276276
return true;
@@ -281,17 +281,18 @@ public Boolean unlock() {
281281

282282
return true;
283283
}
284-
284+
285285
/**
286286
* 获取锁状态
287+
*
288+
* @return
287289
* @Title: isLock
288-
* @return
289290
* @author yuhao.wang
290291
*/
291292
public boolean isLock() {
292-
293-
return locked;
294-
}
293+
294+
return locked;
295+
}
295296

296297
/**
297298
* 重写redisTemplate的set方法
@@ -328,6 +329,26 @@ public String doInRedis(RedisConnection connection) throws DataAccessException {
328329
});
329330
}
330331

332+
/**
333+
* 获取redis里面的值
334+
*
335+
* @param key key
336+
* @param aClass class
337+
* @return T
338+
*/
339+
private <T> T get(final String key, Class<T> aClass) {
340+
Assert.isTrue(!StringUtils.isEmpty(key), "key不能为空");
341+
return redisTemplate.execute((RedisConnection connection) -> {
342+
Object nativeConnection = connection.getNativeConnection();
343+
Object result = null;
344+
if (nativeConnection instanceof JedisCommands) {
345+
result = ((JedisCommands) nativeConnection).get(key);
346+
}
347+
return (T) result;
348+
});
349+
}
350+
351+
331352
/**
332353
* @param millis 毫秒
333354
* @param nanos 纳秒

spring-boot-student-layering-cache/pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
<dependency>
5757
<groupId>com.github.xiaolyuh</groupId>
5858
<artifactId>layering-cache-starter</artifactId>
59-
<version>1.1.0</version>
59+
<version>1.1.3</version>
6060
</dependency>
6161

6262
</dependencies>

0 commit comments

Comments
 (0)