当前位置:新励学网 > 秒知问答 > thinkphp下MySQL数据库读写分离代码剖析

thinkphp下MySQL数据库读写分离代码剖析

发表时间:2024-08-24 17:26:23 来源:网友投稿

当采用原生态的sql语句进行写入操作的时候,要用execute,读操作要用query。

MySQL数据主从同步还是要靠MySQL的机制来实现,所以这个时候MySQL主从同步的延迟问题是需要优化,延迟时间太长不仅影响业务,还影响用户体验。thinkphp核心类Thinkphp/library/Model.class.php 中,query 方法调用Thinkphp/library/Think/Db/Driver/Mysql.class.phppublic 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.phppublic 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表示调用读写分离的读库。protected function initConnect($master=true) {if(1 == C('DB_DEPLOY_TYPE'))// 采用分布式数据库$this->_linkID = $this->multiConnect($master);else// 默认单数据库if ( !$this->connected ) $this->_linkID = $this->connect();}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{// 读操作连接从服务器

免责声明:本站发布的教育资讯(图片、视频和文字)以本站原创、转载和分享为主,文章观点不代表本网站立场。

如果本文侵犯了您的权益,请联系底部站长邮箱进行举报反馈,一经查实,我们将在第一时间处理,感谢您对本站的关注!