/**
* 连接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;
}