下面由thinkphp教程欄目給大家介紹thinkphp lock鎖的使用和例子,希望對需要的朋友有所幫助!
在開發(fā)需求中會遇到這樣一種情況,并發(fā)請求。數(shù)據(jù)庫的更新還沒執(zhí)行結(jié)束,另一個select查出的數(shù)據(jù),會是更新之前的數(shù)據(jù),那就會造成查詢數(shù)據(jù)不準(zhǔn)確。
那怎么解決呢?用innoDB的事務(wù)和鎖就能解決這個問題。在我們當(dāng)前行更新還沒結(jié)束的時候,select查詢此行的數(shù)據(jù)會被鎖起來。
比如我們數(shù)據(jù)庫有這樣兩行數(shù)據(jù)
我們把id=1的num數(shù)據(jù)更新為1000,sleep10秒,這時候我們select id=1的數(shù)據(jù)時,會等待update的更新結(jié)束,如果我們select id=2的時候,不需要等待10秒,會立馬獲取到數(shù)據(jù)。
這就是InnoDB的行鎖,只會鎖當(dāng)前update的那行數(shù)據(jù),不會鎖整表。
下面會列出測試代碼,記得吧引擎改為innoDB,不是MYISAM。
class Index extends Controller { public function index() { $model=Db::name('test'); $model->startTrans(); try{ $list=$model->lock(true)->find(); $model->where(['id'=>1])->data(['num'=>900])->update();//id為1的更新 sleep(10);//等待10秒 $model->commit(); print_r($list); }catch (Exception $exception){ $model->rollback(); throw $exception; } } public function index2(){ $model=Db::name('test'); $model->startTrans(); try{ $list=$model->lock(true)->where(['id'=>1])->find();//id為1在更新時,select id=1 會等待。把ID改為2時,不等待 $model->commit(); print_r($list); }catch (Exception $exception){ $model->rollback(); throw $exception; } } }
測試步驟:請求index后,在請求index2,就會看到index2會等index加載結(jié)束,我們才能看到index2的打印結(jié)果。如果index2的id改為2后,則不會受到index的影響。