@Component
public class DistributedLock {
private static final Logger LOGGER = LoggerFactory.getLogger(DistributedLock.class);
@Resource(name = "cscRedisClient")
private RedisStoreClient redisStoreClient;
private static final String LOCK_CATEGORY = "oms_distribut_lock";
private static final String APP_KEY = "csc-oms-task-process-service";
/**
* 加锁
* @param locaName 锁的key
* @param acquireTimeout 获取超时时间
* @param timeout 锁的超时时间
* @return 锁标识
*/
public String lockWithTimeout(String locaName,
long acquireTimeout, int timeout) {
String retIdentifier = null;
try {
// 随机生成一个value
String identifier = UUID.randomUUID().toString();
// 锁名,即key值
String lockKey = "lock:" + locaName;
// 超时时间,上锁后超过此时间则自动释放锁
// int lockExpire = (int)(timeout / 1000);
// 获取锁的超时时间,超过这个时间则放弃获取锁
long end = System.currentTimeMillis() + acquireTimeout * 1000;
final StoreKey storeKey = new StoreKey(LOCK_CATEGORY, APP_KEY, lockKey);
while (System.currentTimeMillis() < end) {
if (redisStoreClient.setnx(storeKey, identifier)) {
redisStoreClient.expire(storeKey, timeout);
// 返回value值,用于释放锁时间确认
retIdentifier = identifier;
return retIdentifier;
}
// 返回-1代表key没有设置超时时间,为key设置一个超时时间
if (redisStoreClient.ttl(storeKey) == -1) {
redisStoreClient.expire(storeKey, timeout);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} catch (Exception e) {
LOGGER.error("获取锁失败" + locaName, e);
Cat.logError("获取锁失败" + locaName, e);
}
return retIdentifier;
}
/**
* 释放锁
* @param lockName 锁的key
* @param identifier 释放锁的标识
* @return
*/
public boolean releaseLock(String lockName, long acquireTimeout, String identifier) {
String lockKey = "lock:" + lockName;
boolean retFlag = false;
try {
final StoreKey storeKey = new StoreKey(LOCK_CATEGORY, APP_KEY, lockKey);
long end = System.currentTimeMillis() + acquireTimeout * 1000;
while (System.currentTimeMillis() < end) {
if (redisStoreClient.compareAndDelete(storeKey, identifier)) {
LOGGER.info("delelte lock");
break;
}
}
} catch (Exception e) {
LOGGER.warn("releaseLock,{}",e);
}
return retFlag;
}
}