Laravel lockforupdate(悲观锁)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34556511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel lockforupdate (Pessimistic Locking)
提问by user259752
i'm trying to figure out how to use/test the lockforupdate correctly, but i found is not function like what i expected
我试图弄清楚如何正确使用/测试 lockforupdate,但我发现它的功能不像我预期的那样
this is just testing
这只是测试
public function index() {
return dd(\DB::transaction(function() {
if (\Auth::guard('user')->check()) {
$model = \App\Models\User::find(1)->lockForUpdate();
sleep(60);
$model->point = 100000;
$model->save();
} else {
$model = \App\Models\User::find(1);
$model->point = 999;
$model->save();
}
return $model;
}));
}
i try to test in 2 browser, browser 1 user logged in and browser 2 not logged in, browser 1 hit refresh, then there will lockforupdate and sleep 60 seconds before update
我尝试在 2 个浏览器中进行测试,浏览器 1 用户登录而浏览器 2 未登录,浏览器 1 点击刷新,然后会在更新前锁定更新和睡眠 60 秒
in the 60 seconds, i go browser 2 and hit refresh, however the record is not locked, i check phpmyadmin and the record is updated(within the 60 seconds lock trigger by browser 1)
在 60 秒内,我转到浏览器 2 并点击刷新,但记录未锁定,我检查 phpmyadmin 并更新记录(在浏览器 1 触发的 60 秒锁定内)
but after 60 seconds, the record has been modified again by browser 1(Point 100000)
但60秒后,该记录又被浏览器1修改了(Point 100000)
so am i misunderstanding the lockforupdate is use for?or i test it incorrectly?
所以我是不是误解了 lockforupdate 的用途?还是我测试不正确?
what i expected is the row shouldn't be modified by browser 2 in the first 60 seconds(blank page with loading favicon or error throw?)
我期望的是在前 60 秒内浏览器 2 不应修改该行(带有加载图标或错误抛出的空白页面?)
https://laravel.com/docs/5.2/queries#pessimistic-locking
https://laravel.com/docs/5.2/queries#pessimistic-locking
and i did some research but still cannot understand what different between sharedLock(LOCK IN SHARE MODE) and lockForUpdate(FOR UPDATE)
我做了一些研究,但仍然无法理解 sharedLock(LOCK IN SHARE MODE) 和 lockForUpdate(FOR UPDATE) 之间的区别
btw i confirmed the database is innodb
顺便说一句,我确认数据库是 innodb
回答by user259752
This work, finally, but still don't understand what sharedLock(LOCK IN SHARE MODE) and lockForUpdate(FOR UPDATE) different
这项工作,终于,但仍然不明白 sharedLock(LOCK IN SHARE MODE) 和 lockForUpdate(FOR UPDATE) 有什么不同
public function index() {
return dd(\DB::transaction(function() {
if (\Auth::guard('user')->check()) {
$model = \App\Models\User::lockForUpdate()->find(1);
sleep(30);
$model->point = 100000;
$model->save();
} else {
$model = \App\Models\User::lockForUpdate()->find(1);
$model->point = $model->point + 1;
$model->save();
}
return $model;
}));
}