下面由laravel教程栏目给大家laravel高并发之抽奖秒杀解决方案,希望对需要的朋友有所帮助!
测试1.8核16g的服务器jmeter并发2000注意不要在一台机子上测,因为网络的原因,本机上测并发1000不用锁也是正常的。可以在阿里云买台测试机
1.mysql共享锁版sql加共享锁,stock字段减1。返回成功表示成功,返回失败表示自减失败。stock字段是无符号的
迁移文件<?phpuse 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);}
2.reids队列1.lpush加入队列2.lpop弹窗队列,成功返回对应值,不存在返回null以上就是laravel高并发之抽奖秒杀解决方案的详细内容。