php artisan make:job OrderJop 生成任务类,类名自己取
?配置 App\config\queue.php
? ?
<?php
namespace App\Jobs;
use App\Models\GoodsModel;
use App\Models\OrderModel;
use App\Models\SkillModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class OrderJop implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $oid = '';
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($oid,$delay)
{
$this->oid = $oid;
$this->delay($delay);
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
DB::beginTransaction();
try {
$result = OrderModel::where('order_id',$this->oid)->first();
//如果时间到了order_status 还是为 0 未支付 就直接根据订单id 修改订单状态
if ($result['order_status'] == 0){
$res = OrderModel::where('order_id',$this->oid)->update(['order_status'=>1]);//未支付 把 0 改为 1 取消订单
if ($res){
SkillModel::where('goods_id',$result['g_id'])->increment('skill_stock');//回秒杀库存
$skillOneData = SkillModel::where('goods_id',$result['g_id'])->first();
GoodsModel::where('id',$result['g_id'])->update(['goods_stock'=>$skillOneData['skill_stock']]);//同步商品库存
}
}
DB::commit();
}catch (\Exception $e){
DB::rollBack();
}
}
}
订单? 调用orderJop 传参
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
* 创建订单
*/
public function createOrder(Request $request)
{
//抢购用户id
$userID = 5;
//商品id
$goodsID = $request->input("goods_id");
//对应商品抢购成功用户集合 {1,3,4}
$robSuccessUser = "success_user".$goodsID;
//进行判断当前用户是否在抢成功的队列里面
$result = Redis::sismember($robSuccessUser,$userID);
//如果你在这里面,就抢完了
if (!$result) {
//如果抢购成功 返回状态码,进行下单
return response()->json(['errorCode' => 20003, 'data' => '', 'msg' => '手慢了!']);
}
DB::beginTransaction();
try{
//减库存
SkillModel::where('goods_id',$goodsID)->decrement('skill_stock');
$skill_stock = SkillModel::where('goods_id',$goodsID)->first();
GoodsModel::where('id',$goodsID)->update(['goods_stock'=>$skill_stock['skill_stock']]);
$goodsOneData = GoodsModel::where('id',$goodsID)->first();
//生成订单
$arr = [
'u_id'=>$userID,//用户
'g_id'=>$goodsID,//商品
'order_time'=>time(),//时间
'order_no'=>'rb'.time().rand(1111,9999),//订单编号
'order_price'=>$goodsOneData['goods_price'] //金额
];
$res = OrderModel::create($arr);
$bool = OrderModel::where('order_no',$res['order_no'])->first();
DB::commit();
//下单成功,跳转支付页面
$oid = $bool['order_id'];
if ($oid){
$this->dispatch(new orderJob($oid,30));//延迟消息队列
return response()->json(['errorCode' => 0, 'data' => '', 'msg' => '秒杀成功,订单已生成!']);
}
}catch (\Exception $e){
DB::rollBack();
}
启动任务队列:php artisan queue:work 能看到执行成功
如果没有延迟效果? 执行? php artisan config:cache? 清理一下缓存
|