thinkphp5悲观锁抢购

mysql for update悲观锁,只有在事务中才有效

对数据的修改持有悲观态度的并发控制方式。总是假设最坏的情况,每次读取数据的时候都默认其他线程会更改数据,因此需要进行加锁操作,当其他线程想要访问数据时,都需要阻塞挂起。

如何实现抢购

代码1如下

```
DB::name('goods_order')->startTrans();
$check = DB::name('goods_order')->where('goods_id',1)->where('username','138****0731')->lock(true)->count();
if($checkwhere('id', 1)->setInc('sold_number');
Db::table('goods_list')->where('id', 1)->setDec('goods_number');

$time = time();
$sql = "INSERT INTO `goods_order` ( `sid`, `order_sn`, `username`, `goods_id`) VALUES (1, '202201250949', '138****0731', 1);
";
Db::name('goods_order')->execute($sql);
DB::name('goods_order')->commit();
}else{
echo "no";
error_log(print_r("no",1),3,"/tmp/1.txt");
DB::name('goods_order')->rollback();
}
```

代码2如下

```
DB::name('goods_order')->startTrans();
$check = DB::name('goods_list')->field('goods_name,goods_number,sold_number')->where('id',1)->lock(true)->find();
if($check['goods_number']>0){
echo "yes";
$goods_num = $check['goods_number'];
$sold_number = $check['sold_number'];
Db::name('goods_list')->where('id',1)->update(['goods_number'=>$goods_num-1,'sold_number'=>$sold_number+1]);

$time = time();
$sql = "INSERT INTO `goods_order` ( `sid`, `order_sn`, `username`, `goods_id`) VALUES (1, '202201250949', '138****0731', 1);
";
Db::name('goods_order')->execute($sql);

$num = DB::name('goods_order')->where('username','138****0731')->count();
if($num>10){
DB::name('goods_order')->rollback();
}else{
DB::name('goods_order')->commit();
}
}else{
echo "no";
}
```

    A+
发布日期:2022年01月25日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: