关于 Laravel 数据库查询锁必须要知道的知识点
Mysql锁的类型
1 共享锁
* 查询数据
会阻塞
等待没有任何人占用的时候再返回
* 更新数据
会阻塞
等待没有任何人占用的时候再返回
DB::table('users')->where('id', 100)->lockForUpdate()->first();
2 悲观锁
* 查询数据
正常查询返回
* 更新数据
会阻塞
等待上一个锁更新执行完毕后再更新
DB::table('users')->where('id', 100)->sharedLock()->first();
如果我直接使用锁不使用事务能正常逻辑吗?
正确
DB::transaction(function() { $user = DB::table('users')->where('id', 100)->lockForUpdate()->first(); $user->nick_name = "老王"; $user->save(); });
错误
$user = DB::table('users')->where('id', 100)->lockForUpdate()->first(); $user->nick_name = "老王"; $user->save();
原因
锁必须要在事务中进行才能生效
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: