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


Posted in PHP onApril 18, 2017

当采用原生态的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'    => 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);
  }

query方法参数为false,其他删除、更新、增加读主库。这一点可以结合Thinkphp/library/Model.class.php中的delete、save、add操作,参数为true。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
社区(php&&mysql)六
Oct 09 PHP
phpmyadmin config.inc.php配置示例
Aug 27 PHP
PHP面向对象教程之自定义类
Jun 10 PHP
PHP+FastCGI+Nginx配置PHP运行环境
Aug 07 PHP
Yii数据库缓存实例分析
Mar 29 PHP
php自动加载方式集合
Apr 04 PHP
PHP Filter过滤器全面解析
Aug 09 PHP
关于PHP中字符串与多进制转换函数的实例代码
Nov 03 PHP
php+jQuery实现的三级导航栏下拉菜单显示效果
Aug 10 PHP
PHP使用PDO操作sqlite数据库应用案例
Mar 07 PHP
PHP+百度AI OCR文字识别实现了图片的文字识别功能
May 08 PHP
PHP+Redis事务解决高并发下商品超卖问题(推荐)
Aug 03 PHP
Thinkphp通过一个入口文件如何区分移动端和PC端
Apr 18 #PHP
Yii2汉字转拼音类的实例代码
Apr 18 #PHP
php+resumablejs实现的分块上传 断点续传功能示例
Apr 18 #PHP
ZendFramework2连接数据库操作实例
Apr 18 #PHP
PHP实现的数独求解问题示例
Apr 18 #PHP
PHP使用finfo_file()函数检测上传图片类型的实现方法
Apr 18 #PHP
php实现不通过扩展名准确判断文件类型的方法【finfo_file方法与二进制流】
Apr 18 #PHP
You might like
PHP 5.0对象模型深度探索之类的静态成员
2008/03/27 PHP
php读取30天之内的根据算法排序的代码
2008/04/06 PHP
phpMyadmin 用户权限中英对照
2010/04/02 PHP
php 代码优化之经典示例
2011/03/24 PHP
使用php判断浏览器的类型和语言的函数代码
2013/02/28 PHP
php输出金字塔的2种实现方法
2014/12/16 PHP
php中magic_quotes_gpc对unserialize的影响分析
2014/12/16 PHP
如何利用http协议发布博客园博文评论
2015/08/03 PHP
JavaScript事件处理器中的event参数使用介绍
2013/05/24 Javascript
JavaScript如何实现在文本框(密码框)输入提示语
2015/12/25 Javascript
为什么JavaScript没有块级作用域
2016/05/22 Javascript
js拖拽功能实现代码解析
2016/11/28 Javascript
从源码看angular/material2 中 dialog模块的实现方法
2017/10/18 Javascript
element ui里dialog关闭后清除验证条件方法
2018/02/26 Javascript
jQuery基于Ajax实现读取XML数据功能示例
2018/05/31 jQuery
浅谈Webpack下多环境配置的思路
2018/06/27 Javascript
原生javascript实现连连看游戏
2019/01/03 Javascript
Vue项目使用localStorage+Vuex保存用户登录信息
2019/05/27 Javascript
JavaScript实现点击自制菜单效果
2021/02/02 Javascript
[03:56]显微镜下的DOTA2第十一期——鬼畜的死亡先知播音员
2014/06/23 DOTA
使用Python内置模块与函数进行不同进制的数的转换
2020/04/26 Python
Python通过format函数格式化显示值
2020/10/17 Python
广州御银科技股份有限公司试卷(C++)
2016/11/04 面试题
车队司机自我鉴定
2014/03/02 职场文书
产品销售计划书
2014/05/04 职场文书
领导干部查摆“四风”问题自我剖析材料思想汇报
2014/10/05 职场文书
中班下学期幼儿评语
2014/12/30 职场文书
后进生评语大全
2015/01/04 职场文书
华山导游词
2015/02/03 职场文书
2015年前台接待工作总结
2015/05/04 职场文书
单身证明范本
2015/06/15 职场文书
关于做家务的心得体会
2016/01/23 职场文书
大学生创业计划书常用模板
2019/08/07 职场文书
Python序列化与反序列化相关知识总结
2021/06/08 Python
Node与Python 双向通信的实现代码
2021/07/16 Javascript
nginx代理实现静态资源访问的示例代码
2022/07/07 Servers