

sql加共享锁,stock字段减1。返回成功表示成功,返回失败表示自减失败。stock字段是无符号的
<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
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 AppModelsStockTest();
$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);
}lpush加入队列lpop弹窗队列,成功返回对应值,不存在返回null