Home >PHP Framework >Laravel >laravel high concurrency lottery flash sale solution

laravel high concurrency lottery flash sale solution

藏色散人
藏色散人forward
2020-06-18 13:34:214807browse

The following tutorial column from Laravel will give you laravel’s high concurrency lottery flash sale solution. I hope it will be helpful to friends in need!

laravel high concurrency lottery flash sale solution

test

  • 1.<span style="font-size: 16px;">8-core 16G</span> server<span style="font-size: 16px;">Jmeter</span>Concurrency<span style="font-size: 16px;">2000</span>

Note

Do not Testing on a computer. Due to network reasons, it is normal to test concurrency of <span style="font-size: 16px;">1000</span> without locking on this machine. You can buy a test machine on Alibaba Cloud

1.mysql shared lock version

sql plus shared lock, stock Decrease the field by 1. Returning success means success, returning failure means decrement failed. The stock field is unsigned

Migration file

<?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(&#39;stock_test&#39;, function (Blueprint $table) {
            $table->increments(&#39;id&#39;);
            $table->integer(&#39;stock&#39;)->default(0)->comment(&#39;库存1&#39;);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists(&#39;stock_test&#39;);
    }
}

Code

$model = new \App\Models\StockTest();
$id = $request->input(&#39;id&#39;,1);

try {
    // 手动开始事务
    DB::beginTransaction();
    // sql加共享锁,stock字段减1。返回成功表示成功,返回失败表示自减失败。stock字段是无符号的
    $is = DB::table(&#39;stock_test&#39;)->lockForUpdate()->increment(&#39;stock&#39;,-1);
    if($is)
    {
        log_info(&#39;id=&#39;.$id.&#39;库存减1&#39;);
        // 提交事务
        DB::commit();
        return response(&#39;成功&#39;,200);
    }
    else
    {
        return response(&#39;失败&#39;,201);
    }
} catch (\Exception $exception) {
    // 回滚事务
    DB::rollBack();
    return response(&#39;失败&#39;,201);
}

2.reids queue

  • 1.<span style="font-size: 16px;">lpush</span>Join queue
  • 2.<span style="font-size: 16px;">lpop</span>Pop-up queue, the corresponding value is returned successfully, if it does not exist, it returns <span style="font-size: 16px;">null</span>

The above is the detailed content of laravel high concurrency lottery flash sale solution. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete