>  기사  >  PHP 프레임워크  >  thinkphp에서 데이터베이스 읽기 및 쓰기 분리 코드 분석

thinkphp에서 데이터베이스 읽기 및 쓰기 분리 코드 분석

藏色散人
藏色散人앞으로
2020-08-20 13:28:572961검색

thinkphp프레임워크 튜토리얼의 다음 칼럼에서는 thinkphp에서 데이터베이스 읽기 및 쓰기 분리에 대한 코드 분석을 소개합니다. 도움이 필요한 친구들에게 도움이 되길 바랍니다!

thinkphp에서 데이터베이스 읽기 및 쓰기 분리 코드 분석

  • 쓰기 작업에는 원본 SQL 문을 사용할 때 실행이 사용되고 읽기 작업에는 쿼리가 사용됩니다.

  • MySQL 데이터 마스터-슬레이브 동기화는 여전히 MySQL 메커니즘에 의존하므로 MySQL 마스터-슬레이브 동기화의 지연 문제는 현 시점에서 최적화되어야 합니다. 너무 긴 지연 시간은 비즈니스에 영향을 미칠 뿐만 아니라 영향을 미칩니다. 사용자 경험.

Thinkphp 코어 클래스 Thinkphp/library/Model.class.php, 쿼리 메소드,

Thinkphp/library/Think/Db/Driver/Mysql.class.php

  /**
     * SQL查询
     * @access public
     * @param string $sql  SQL
     * @param mixed $parse  是否需要解析SQL  
     * @return mixed
     */
    public function query($sql,$parse=false) {
        if(!is_bool($parse) && !is_array($parse)) {
            $parse = func_get_args();
            array_shift($parse);
        }
        $sql  =   $this->parseSql($sql,$parse);
        return $this->db->query($sql);
    }

호출 Thinkphp/library/Think/Db / Driver/Mysql.class.php

  /**
     * 执行查询 返回数据集
     * @access public
     * @param string $str  sql指令
     * @return mixed
     */
    public function query($str) {
        if(0===stripos($str, 'call')){ // 存储过程查询支持
            $this->close();
            $this->connected    =   false;
        }
        $this->initConnect(false);
        if ( !$this->_linkID ) return false;
        $this->queryStr = $str;
        //释放前次的查询结果
        if ( $this->queryID ) {    $this->free();    }
        N('db_query',1);
        // 记录开始执行时间
        G('queryStartTime');
        $this->queryID = mysql_query($str, $this->_linkID);
        $this->debug();
        if ( false === $this->queryID ) {
            $this->error();
            return false;
        } else {
            $this->numRows = mysql_num_rows($this->queryID);
            return $this->getAll();
        }
    }

위의 데이터베이스 링크를 초기화할 때 initConnect(false)가 Thinkphp/library/Think/Db/Db.class.php를 호출하는데, false와 true 코드 구현에 주의하세요. true는 메인 라이브러리를 직접 호출하는 것을 의미하고, false는 읽기와 쓰기를 별도로 호출하여 읽기 라이브러리를 호출하는 것을 의미합니다.

  /**
     * 初始化数据库连接
     * @access protected
     * @param boolean $master 主服务器
     * @return void
     */
    protected function initConnect($master=true) {
        if(1 == C('DB_DEPLOY_TYPE'))
            // 采用分布式数据库
            $this->_linkID = $this->multiConnect($master);
        else
            // 默认单数据库
            if ( !$this->connected ) $this->_linkID = $this->connect();
    }
    /**
     * 连接分布式服务器
     * @access protected
     * @param boolean $master 主服务器
     * @return void
     */
    protected function multiConnect($master=false) {
        foreach ($this->config as $key=>$val){
            $_config[$key]      =   explode(',',$val);
        }        
        // 数据库读写是否分离
        if(C('DB_RW_SEPARATE')){
            // 主从式采用读写分离
            if($master)
                // 主服务器写入
                $r  =   floor(mt_rand(0,C('DB_MASTER_NUM')-1));
            else{
                if(is_numeric(C('DB_SLAVE_NO'))) {// 指定服务器读
                    $r = C('DB_SLAVE_NO');
                }else{
                    // 读操作连接从服务器
                    $r = floor(mt_rand(C('DB_MASTER_NUM'),count($_config['hostname'])-1));   // 每次随机连接的数据库
                }
            }
        }else{
            // 读写操作不区分服务器
            $r = floor(mt_rand(0,count($_config['hostname'])-1));   // 每次随机连接的数据库
        }
        $db_config = array(
            'username'  =>  isset($_config['username'][$r])?$_config['username'][$r]:$_config['username'][0],
            'password'  =>  isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0],
            'hostname'  =>  isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0],
            'hostport'  =>  isset($_config['hostport'][$r])?$_config['hostport'][$r]:$_config['hostport'][0],
            'database'  =>  isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0],
            'dsn'       =>  isset($_config['dsn'][$r])?$_config['dsn'][$r]:$_config['dsn'][0],
            'params'    =>  isset($_config['params'][$r])?$_config['params'][$r]:$_config['params'][0],
            'charset'   =>  isset($_config['charset'][$r])?$_config['charset'][$r]:$_config['charset'][0],            
        );
        return $this->connect($db_config,$r);
    }

쿼리 메소드 매개변수가 false이고 다른 사람들은 기본 읽기 라이브러리를 삭제, 업데이트 및 추가합니다. 이는 Thinkphp/library/Model.class.php의 삭제, 저장 및 추가 작업과 결합될 수 있으며 매개변수는 true입니다.

위 내용은 thinkphp에서 데이터베이스 읽기 및 쓰기 분리 코드 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제