Thinkphp文件锁处理高并发

来源:互联网 发布:无线路由器破解软件 编辑:程序博客网 时间:2024/06/08 17:27
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;
    }
}
原创粉丝点击