下面由thinkphp教程欄目給大家介紹thinkphp lock鎖的使用和例子,希望對需要的朋友有所幫助!
在開發(fā)需求中會遇到這樣一種情況,并發(fā)請求。數據庫的更新還沒執(zhí)行結束,另一個select查出的數據,會是更新之前的數據,那就會造成查詢數據不準確。
那怎么解決呢?用innoDB的事務和鎖就能解決這個問題。在我們當前行更新還沒結束的時候,select查詢此行的數據會被鎖起來。
比如我們數據庫有這樣兩行數據
我們把id=1的num數據更新為1000,sleep10秒,這時候我們select id=1的數據時,會等待update的更新結束,如果我們select id=2的時候,不需要等待10秒,會立馬獲取到數據。
這就是InnoDB的行鎖,只會鎖當前update的那行數據,不會鎖整表。
下面會列出測試代碼,記得吧引擎改為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加載結束,我們才能看到index2的打印結果。如果index2的id改為2后,則不會受到index的影響。