diff --git a/.gitignore b/.gitignore index c867e8f..9091e68 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,5 @@ vendor/ .env .DS_Store *.lock -.phpunit* \ No newline at end of file +.phpunit* +/watch diff --git a/app/Controller/CouponController.php b/app/Controller/CouponController.php index bf1bd41..069c9a2 100644 --- a/app/Controller/CouponController.php +++ b/app/Controller/CouponController.php @@ -98,35 +98,36 @@ class CouponController extends BaseController $userId = $this->request->input("user_id"); $receiveType = $this->request->input("receive_type"); $ids = $this->request->input("ids"); - $test = $this->request->input("test", 0); - $ids = explode(',', $ids); - $cps = Coupon::whereIn('id', $ids)->get(); $now = time(); $success = []; $fail = []; - foreach ($cps as $key => $cp) { - $crt = CouponUserRecType::where( - [ - 'system_coupon_user_id' => $cp->id, - 'receive_type' => $receiveType - ] - )->first(); - - $cr = new CouponRec; - $cr->user_id = $userId; - $cr->system_coupon_user_id = $cp->id; - $cr->order_main_id = 0; - $cr->receive_time = $now; - $cr->number = $crt->one_receive_number; - $cr->number_remain = $crt->one_receive_number; - $cr->status = 0; - $cr->update_time = $now; - $cr->receive_type = $receiveType; - if ($test && ($cp->id % 2)) { - $fail[] = $cp; - } else { - //TODO 会有超发情况 + + + Db::transaction(function () use ($ids,$receiveType,$userId,&$success,&$fail,$now) { + //读写锁,完全控制,性能底 + $cps = Coupon::whereIn('id', $ids)->lockForUpdate()->get(); + //写锁,可能在高并发下,读取到脏数据,写入可能有超发情况 + //$cps = Coupon::whereIn('id', $ids)->sharedLock()->get(); + + foreach ($cps as $key => $cp) { + $crt = CouponUserRecType::where( + [ + 'system_coupon_user_id' => $cp->id, + 'receive_type' => $receiveType + ] + )->first(); + + $cr = new CouponRec; + $cr->user_id = $userId; + $cr->system_coupon_user_id = $cp->id; + $cr->order_main_id = 0; + $cr->receive_time = $now; + $cr->number = $crt->one_receive_number; + $cr->number_remain = $crt->one_receive_number; + $cr->status = 0; + $cr->update_time = $now; + $cr->receive_type = $receiveType; //如果优惠卷库存小于等于已领取的数量, 则返回领取失败的优惠券 if ($cp->inventory<=$cp->inventory_use||$cp->inventory<($cp->inventory_use+$cr->number)){ $fail[] = $cp; @@ -139,8 +140,7 @@ class CouponController extends BaseController } } } - - } + }); return $this->success([ 'success' => $success, diff --git a/app/Controller/IndexController.php b/app/Controller/IndexController.php index 60c3235..3864423 100644 --- a/app/Controller/IndexController.php +++ b/app/Controller/IndexController.php @@ -20,7 +20,7 @@ class IndexController extends AbstractController return [ 'method' => $method, - 'message' => "Hello {$user}.", + 'message' => "Hello22222 {$user}.", ]; } }