首頁 >php框架 >ThinkPHP >介紹thinkphp lock鎖的使用與例子

介紹thinkphp lock鎖的使用與例子

藏色散人
藏色散人轉載
2021-05-12 17:15:334649瀏覽

下面由thinkphp教學欄位來介紹thinkphp lock鎖定的使用和例子,希望對需要的朋友有幫助!

介紹thinkphp lock鎖的使用與例子

#在開發需求中會遇到這樣一種情況,並發請求。資料庫的更新還沒執行結束,另一個select查出的數據,會是更新先前的數據,那就會造成查詢數據不準確。

那要怎麼解決呢?用innoDB的事務和鎖定就能解決這個問題。在我們目前行更新還沒結束的時候,select查詢此行的資料會被鎖起來。

例如我們資料庫有這樣兩行資料
介紹thinkphp lock鎖的使用與例子
我們把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的影響。

相關推薦:最新的10個thinkphp影片教學

#

以上是介紹thinkphp lock鎖的使用與例子的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除