下面由laravel教程栏目给大家laravel高并发之抽奖秒杀解决方案,希望对需要的朋友有所帮助!
不要在一台机子上测,因为网络的原因,本机上测并发1000不用锁也是正常的。可以在阿里云买台测试机
sql加共享锁,stock字段减1。返回成功表示成功,返回失败表示自减失败。stock字段是无符号的
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateStockTestTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('stock_test', function (Blueprint $table) { $table->increments('id'); $table->integer('stock')->default(0)->comment('库存1'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('stock_test'); } }
$model = new \App\Models\StockTest(); $id = $request->input('id',1); try { // 手动开始事务 DB::beginTransaction(); // sql加共享锁,stock字段减1。返回成功表示成功,返回失败表示自减失败。stock字段是无符号的 $is = DB::table('stock_test')->lockForUpdate()->increment('stock',-1); if($is) { log_info('id='.$id.'库存减1'); // 提交事务 DB::commit(); return response('成功',200); } else { return response('失败',201); } } catch (\Exception $exception) { // 回滚事务 DB::rollBack(); return response('失败',201); }
以上就是laravel高并发之抽奖秒杀解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号