Authored by Lixiaodi

加分布式锁

... ... @@ -66,14 +66,14 @@ public class RedisValueCache {
* @param key
* @param value
*/
public <T> void setIfAbsent(String key, T value) {
public <T> boolean setIfAbsent(String key, T value) {
String v = RedisUtil.value2String(value);
if (v == null) {
log.warn("setIfAbsent redis error with key={}, value={}", key, value);
return;
return false;
}
RedisKeyBuilder redisKeyBuilder = RedisKeyBuilder.newInstance().appendFixed(key);
yhValueOperations.setIfAbsent(redisKeyBuilder, v);
return yhValueOperations.setIfAbsent(redisKeyBuilder, v);
}
/**
... ...
... ... @@ -255,6 +255,7 @@ public class UnionServiceImpl implements IUnionService,ApplicationEventPublisher
public UnionResponse activateUnion(ActivateUnionRequestBO request) throws ServiceException {
String ut = null;
String k = null;
boolean getLock = false;
try {
activeUnion.info("activateUnion with request is {}", request);
// 检查输入参数
... ... @@ -408,7 +409,8 @@ public class UnionServiceImpl implements IUnionService,ApplicationEventPublisher
ut = click.getUnion_type();
k = key;
if (!getDistributeLock(ut, k)) {
getLock = getDistributeLock(ut, k);
if (!getLock) {
log.info("getDistributeLock failed key is {}", key);
return new UnionResponse(200, "getDistributeLock failed", new JSONObject());
}
... ... @@ -682,7 +684,9 @@ public class UnionServiceImpl implements IUnionService,ApplicationEventPublisher
log.error("activateUnion error with request={}", request, e);
return new UnionResponse(200, e.getMessage(),new JSONObject());
} finally {
deleteDistributeLock(ut, k);
if (getLock) {
deleteDistributeLock(ut, k);
}
}
}
... ... @@ -1466,7 +1470,10 @@ public class UnionServiceImpl implements IUnionService,ApplicationEventPublisher
private boolean getDistributeLock(String unionType, String deviceType) {
String key = UNION_KEY + "NX:" + unionType + ":" + deviceType;
try {
yhValueOperations.setIfAbsent(key, "lock");
boolean lock = yhValueOperations.setIfAbsent(key, "lock");
if (!lock) {
return false;
}
redisTemplate.longExpire(key, 30, TimeUnit.SECONDS);
return true;
} catch (Exception e) {
... ...
... ... @@ -59,7 +59,11 @@ public class UnionClickCountDayTask {
String value = Long.toString(System.nanoTime()) + Long.toString(new Random().nextInt(Integer.MAX_VALUE));
logger.info("UnionClickCountDayTask run time={} , exKey={}, exValue={}", format.format(new Date()), key, value);
redisValueCache.setIfAbsent(key, value);
boolean lock = redisValueCache.setIfAbsent(key, value);
if (!lock) {
logger.info("get lock failed {}", key);
return;
}
String getValue = redisValueCache.get(key, String.class);
logger.info("UnionClickCountDayTask run time={} , getKeyValue={}", format.format(new Date()), getValue);
if (getValue != null && getValue.equals(value)) {
... ...