这是在一个方法调用下面代码的部分
if (!this.checkSoldCountByRedisDate(key, limitCount, buyCount, endDate)) {// 标注10:
throw new ServiceException("您购买的商品【" + commodityTitle + "】,数量已达到活动限购量");
}
2、下面是判断超卖的方法
//标注:1;synchronized
private synchronized boolean checkSoldCountByRedisDate(String key, int limitCount, int buyCount, Date endDate) {
boolean flag = false;
if (redisUtil.exists(key)) {//标注:2;redisUtil.exists(key)
Integer soldCount = (int) redisUtil.get(key);//标注:3;redisUtil.get(key)
Integer totalSoldCount = soldCount + buyCount;
if (limitCount > (totalSoldCount)) {
flag = false;//标注:4;flag = false
} else {
if (redisUtil.tryLock(key, 80)) {//标注:5;rdisUtil.tryLock(key, 80)
redisUtil.remove(key);// 解锁 //标注:6;redisUtil.remove(key)
redisUtil.set(key, totalSoldCount);//标注:7;redisUtil.set(key, totalSoldCount)
flag = true;
} else {
throw new ServiceException("活动太火爆啦,请稍后重试");
}
}
} else {
//标注:8;redisUtil.set(key, new String("buyCount"), DateUtil.diffDateTime(endDate, new Date()))
redisUtil.set(key, new String("buyCount"), DateUtil.diffDateTime(endDate, new Date()));
flag = false;
}
return flag;
}
3、上面提到的redisUtil类中的方法,其中redisTemplate为org.springframework.data.redis.core.RedisTemplate;这个不了解的可以去网上找下,spring-data-redis.jar的相关文档,贴出来redisUtil用到的相关方法:
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
public boolean tryLock(String key, long timeout) {
boolean isSuccess = redisTemplate.opsForValue().setIfAbsent(key, "");
if (isSuccess) {//标注:9;redisTemplate.expire
redisTemplate.expire(key, timeout, TimeUnit.MILLISECONDS);
}
return isSuccess;
}
public Object get(final String key) {
Object result = null;
ValueOperations operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
public boolean set(final String key, Object value) {
return set(key, value, null);
}
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations operations = redisTemplate.opsForValue();
operations.set(key, value);
if (expireTime != null) {
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
}
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}



