排他锁,请求各位大神指点
1. 运行环境
liunx
1). 当前使用的 Laravel 版本?
laravel9
//: <> (使用 php artisan --version
命令查看)
2). 当前使用的 php/php-fpm 版本?
PHP 版本:
8.1
//: <> (使用 php --version
命令查看 php 版本)
1. 问题描述?
排他锁,是否可以这样使用。
DB::beginTransaction();
try {
$order = Order::LockForUpdate()->where('order_sn', 订单号)->first();
$order->update($date);
$order->user->LockForUpdate()->increment('sum', $this->collection->get('amount'));
$order->user->notify(new UserOrder($order));
$order->user->increment('notification_count');
DB::commit();
} catch (\Exception $exception) {
Log::info($exception->getMessage() ?? $this->collection->get('order_sn') . '订单处理失败');
DB::rollBack();
}
在反响关联的时候加锁,这样是否合理。?
订单表Order加锁了。
Order::LockForUpdate()
修改用户表User时候也加锁。
$order->user->LockForUpdate()
2. 您期望得到的结果?
希望在修改订单的时候禁止其他用户修改订单信息
同时修改用户金额的时候也禁止修改用户的金额
//: <> (能截图就截图。)
如果只是当前事务并发的话,这段我认为,只需要第一句话加锁就行了,后续加锁意义不大,整个事务阶段由于第一段加锁,其他事务在获取第一句话的就被阻塞了。