栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 用redis如何处理电商平台,秒杀、抢购超卖

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 用redis如何处理电商平台,秒杀、抢购超卖

这是在一个方法调用下面代码的部分

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;
	}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/778633.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号