1. 程式人生 > 實用技巧 >thinkphp lock 鎖 的使用和例子

thinkphp lock 鎖 的使用和例子

在開發需求中會遇到這樣一種情況,併發請求。資料庫的更新還沒執行結束,另一個select查出的資料,會是更新之前的資料,那就會造成查詢資料不準確。
那怎麼解決呢?用innoDB的事務和鎖就能解決這個問題。在我們當前行更新還沒結束的時候,select查詢此行的資料會被鎖起來。

比如我們資料庫有這樣兩行資料

我們把id=1的num資料更新為1000,sleep10秒,這時候我們select id=1的資料時,會等待update的更新結束,如果我們select id=2的時候,不需要等待10秒,會立馬獲取到資料。
這就是InnoDB的行鎖,只會鎖當前update的那行資料,不會鎖整表。
下面會列出測試程式碼,記得吧引擎改為innoDB,不是MYISAM。

{
    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的影響