// 点击秒杀商品,进入抢购方法
public function price(Request $request)
{
$data = $request->input();
array_shift($data);
unset($data['order']);
// 查出订单表是否有此用户
$user = Order::where('user_id',$data['user_id'])->get()->toarray();
// 如存在拒绝请求,返回数据
if (!empty($user)){
return ['code'=>302,'msg'=>'你已抢过了'];
}
// 查出当前商品的库存按商品id循环存如redis队列,这一步应在添加商品的时候做操作
$goods = Goods::find($data['goods_id'])->toarray();
for(!$i=1; $i <= $goods['invertory']; $i++){
Redis::lpush($goods['id'], $i);
}
// redis队列库存消耗一个
$count = Redis::rpop($goods['id']);
// 如果消耗之后,队列为0说明订单已经满了,返回提示
if($count != 0){
return self::doOrder($data);
} else {
return ['code'=>302,'msg'=>'无库存'];
}
}
//没满走订单创建
public function doOrder($goodsNum)
{
// 生成唯一订单号
$orderNo = $this->orderNo();
// 订单号入订单信息
$goodsNum['order_sn'] = $orderNo;
try {
\DB::beginTransaction(); //启动事务
// 入库之后查出此条数据,接口返回
$data = Order::create($goodsNum)->toarray();
$order = Order::find($data['id']);
\DB::commit(); //提交事务
return ['code'=>200,'msg'=>'成功','data'=>$order];
} catch (Exception $e) {
\DB::rollBack();
return ['code'=>400,'msg'=>'失败'];
}
}
//生成唯一订单号
public function orderNo()
{
return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}
// 当用户将订单提交之后进行商品表库存减一
public function orderForm(Request $request)
{
$id = $request->input('id');
$data = Goods::find($id);
$data->invertory = $data->invertory-1;
$data->save();
return ['code'=>200,'msg'=>'库存已减'];
}
//laravel8阻止接口频繁请求
Route::prefix('goods')->middleware('throttle:1000,1')->group(function (){