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