龙空技术网

laravel高并发之抽奖秒杀解决方案

php中文网 141

前言:

眼前姐妹们对“php 抽奖算法”大约比较讲究,看官们都想要了解一些“php 抽奖算法”的相关文章。那么小编同时在网上网罗了一些关于“php 抽奖算法””的相关内容,希望同学们能喜欢,你们一起来学习一下吧!

测试

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

标签: #php 抽奖算法 #php 抽奖 bug