1、这是在一个方法调用下面代码的部分:
- 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用到的相关方法:
- /**
- * 判断缓存中是否有对应的value
- *
- * @param key
- * @return
- */
- public boolean exists(final String key) {
- return redisTemplate.hasKey(key);
- }
- /**
- * 将键值对设定一个指定的时间timeout.
- *
- * @param key
- * @param timeout
- * 键值对缓存的时间,单位是毫秒
- * @return 设置成功返回true,否则返回false
- */
- public boolean tryLock(String key, lo