thinkphp3.2文件鎖解決並發的一種辦法


使用文件鎖的方法解決

namespace app\index\controller;
use think\Controller;
use think\Cache;


class Index extends Controller
{
   
    /**
     * 首頁
     * */
    public function index(){


        $fp = fopen("lock.txt", "w+");
        if(flock($fp,LOCK_EX))   //鎖定當前指針,,,
        {
            //..處理訂單


            $stock = $this->findStock();
            if($stock > 0){
                $this->setDec();
            }else{
                return '搶購失敗';
            }
            return $stock;
            flock($fp,LOCK_UN);
        }
        fclose($fp);
    }


    /**
     * 查詢數據庫庫存
     * */
    public function findStock(){
        $res = db('info')->where('id',1)->field('stock')->lock(true)->find();
        return $res['stock'];
    }


    /**
     * 減少庫存操作
     * */
    public function setDec(){
        $res = db('info')->where('id',1)->setDec('stock',1);
        return $res;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM