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

发布时间:2025-11-09 点击:26
下面由thinkphp框架教程栏目给大家介绍thinkphp下数据库读写分离代码剖析,希望对需要的朋友有所帮助!
当采用原生态的sql语句进行写入操作的时候,要用execute,读操作要用query。
mysql数据主从同步还是要靠mysql的机制来实现,所以这个时候mysql主从同步的延迟问题是需要优化,延迟时间太长不仅影响业务,还影响用户体验。
thinkphp核心类thinkphp/library/model.class.php 中,query 方法,
调用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' =>

购买云服务器域名做小程序多少钱
php下fopen中文文件名乱码怎么办?
阿里云服务器ecs全部课程
刚才本来近来是要新增备案的
外国ecs云服务器后台说明
网站微信端乱码-虚拟主机/数据库问题
国内外域名存在着什么差异性?新手需要了解什么内容?
怎么向阿里云服务器发送文件