秒杀(基于Thinkphp)(PHP)

/**
 * 连接redis
 */
public function redis() {
	$redis = new Redis();
	$redis->connect('127.0.0.1', 6379);
	return $redis;
}

1、后台添加秒杀商品(秒杀库存添加入redis的队列中)

/**
 * 秒杀库存添加入redis的队列中
 * @param string $unique 商品规格sku唯一值
 * @param int $number 库存个数
 * @param bool $isPush 是否放入之前删除当前队列
 * @return bool|int
 */
public function pushSeckillStock(string $unique, int $number, bool $isPush = false) {
	$name = 'seckill_' . $unique;
	if (!$isPush) {
		$this->redis()->del($name);
	}
	for ($i = 1; $i <= $number; $i++) {
		$this->redis()->lPush($name, $i);
	}
	return true;
}

2、订单确认(缓存订单信息)

/**
 * 缓存订单信息
 * @param $uid
 * @param $cartInfo 购物车内商品
 * @param $priceGroup 价格等信息
 * @param array $other
 * @param int $cacheTime
 * @return string
 * @throws \Psr\SimpleCache\InvalidArgumentException
 */
public function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600) {
	$key = $this->getCacheKey();//雪花算法生成唯一key
	$this->redis()->set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
	return $key;
}

3、前端进行秒杀下单(获取缓存订单信息)判断订单是否过期 

/**
 * 获取订单缓存信息
 * @param int $uid
 * @param string $key
 * @return |null
 */
public function getCacheOrderInfo(int $uid, string $key) {
	$cacheName = 'user_order_' . $uid . $key;
	if (!$this->redis()->has($cacheName))
		return null;
	return $this->redis()->get($cacheName);
}

4、前端进行秒杀下单(弹出redis队列中的库存条数)

/**
 * 弹出redis队列中的库存条数
 * @param string $unique
 * @param int $number
 * @return mixed
 */
public function popSeckillStock(string $unique, int $number = 1) {
	$name = 'seckill_' . $unique;
	if ($number > $this->redis()->lLen($name)) {
		return false;
	}
	for ($i = 1; $i <= $number; $i++) {
		$this->redis()->lPop($name);
	}
	return true;
}

5、取消订单回滚库存

/**
 * 回滚库存
 * @param array $cartInfo
 * @param int $number
 * @return bool
 */
public function rollBackStock(array $cartInfo) {
	$res = true;
	foreach ($cartInfo as $item) {
		$value = $item['cart_info'];
		if ($value['seckill_id']) {
			$res = $res && $this->pushSeckillStock($value['product_attr_unique'], 1, (int)$value['cart_num'], true);
		}
	}
	return $res;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值