分布式锁更新

This commit is contained in:
udf_admin@163.com
2018-01-10 01:49:26 +08:00
parent a20bfe9206
commit 35050dc01b
2 changed files with 86 additions and 2 deletions
@@ -0,0 +1,21 @@
package org.itkk.udf.cache.redis.lock;
import lombok.Data;
import lombok.ToString;
/**
* LockResult
*/
@Data
@ToString
public class LockResult {
/**
* lock
*/
private Boolean lock = false;
/**
* value
*/
private String value;
}
@@ -32,6 +32,59 @@ public class RedisBasedDistributedLock {
@Autowired
private CacheRedisProperties cacheRedisProperties;
/**
* lockAndGet
*
* @param name name
* @param timeout timeout
* @param timeUnit timeUnit
* @param lockValue lockValue
* @return LockResult
*/
public LockResult lockAndGet(String name, long timeout, TimeUnit timeUnit, String lockValue) {
//定义返回值
LockResult lockResult = new LockResult();
//获得key
String key = getKey(name);
//检查是否是死锁
if (redisTemplate.hasKey(key)) {
//获得缓存过期时间
long expiration = redisTemplate.getExpire(key);
//如果等于-1,则代表死锁
if (expiration == -1) {
//删除缓存
redisTemplate.delete(key);
} else {
//获得缓存值
Object cacheValue = redisTemplate.opsForValue().get(key);
//设置返回值
lockResult.setLock(false);
lockResult.setValue(cacheValue == null ? null : (String) cacheValue);
}
} else {
//创建锁
boolean lock = redisTemplate.opsForValue().setIfAbsent(key, lockValue);
//锁成功
if (lock) {
//设置超时时间
redisTemplate.expire(key, timeout, timeUnit);
//设置返回值
lockResult.setLock(true);
lockResult.setValue(lockValue);
} else {
//获得缓存值
Object cacheValue = redisTemplate.opsForValue().get(key);
//设置返回值
lockResult.setLock(false);
lockResult.setValue(cacheValue == null ? null : (String) cacheValue);
}
}
//日志输出
log.info("RedisBasedDistributedLock : lock key : {} : {}", key, lockResult.toString());
//返回
return lockResult;
}
/**
* lock
*
@@ -44,7 +97,7 @@ public class RedisBasedDistributedLock {
*/
public <T> boolean lock(String name, long timeout, TimeUnit timeUnit, T lockValue) {
//获得key
String key = cacheRedisProperties.getPrefix() + DISTRIBUTED_LOCK_KEY_PREFIX + name;
String key = getKey(name);
//检查是否是死锁
if (redisTemplate.hasKey(key)) {
//获得缓存过期时间
@@ -75,11 +128,21 @@ public class RedisBasedDistributedLock {
*/
public void unlock(String name) {
//获得key
String key = cacheRedisProperties.getPrefix() + DISTRIBUTED_LOCK_KEY_PREFIX + name;
String key = getKey(name);
//删除缓存
redisTemplate.delete(key);
//日志输出
log.info("RedisBasedDistributedLock : unlock key : {}", key);
}
/**
* getKey
*
* @param name name
* @return String
*/
private String getKey(String name) {
return cacheRedisProperties.getPrefix() + DISTRIBUTED_LOCK_KEY_PREFIX + name;
}
}