方式一、读写分离(select关键字方式)

<?php
class Db
{
  private $res;
  function __construct($sql)
  {
    $querystr = strtolower(trim(substr($sql,0,6)));  //截取SQL语句字符串
    //如果是select,就连接slave(从)服务器
    if($querystr == 'select')
    {
      $res=$this->slave ($sql);
      $this->res=$res;
    }
    //如果不是select,就连接master(主)服务器
    else
    {
      $res=$this->master ($sql);
      $this->res=$res;
    }
  }

  /**
   * slave从库返回sql查询结果
   * @param $sql
   * @return array
   */
  private function slave ($sql){
//由于现实中读服务器的数量可能在一个以上 会引出负载均衡问题 这里就不做阐述了 从服务器IP我就随机获取了
    $slave_ip=$this->get_slave_ip();
    $dsn="mysql:host=$slave_ip;dbname=fyzq_cloudsys";
    $user='root2';
    $pass='Yd3vlJPuMmDl';
    $dbh=new PDO($dsn, $user, $pass);
    return $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
  }

  /**master主库返回sql执行结果
   * @param $sql
   * @return int
   */
  private function master ($sql){
    $master_ip='127.0.0.1';
    $dsn="mysql:host=$master_ip;dbname=cloudsys";
    $user='root2';
    $pass='Yd3vlJPuMmDl';
    $dbh=new PDO($dsn, $user, $pass);
    return $dbh->exec($sql);
  }

  /**
   * 随机获取slave-ip
   * @return mixed
   */
  private function get_slave_ip(){
    $slave_ips=['127.0.0.1'];//读服务器的ip列表 $slave_ips=['192.168.0.1','192.168.0.2'];
    $count=count($slave_ips)-1;
    $index =mt_rand(0,$count);
    return $slave_ips[$index];
  }

  /**       
   * 获取结果
   * @return int
   */
  public function get_res(){
    return $this->res;
  }
}
 /*
$sql1 = "select * from ecs_goods_info ";
$sql2 = "insert into ecs_goods_info (goods_name) values ('haha')";
$sql3 = "delete from ecs_goods_info where id=199";
$sql4 = "update ecs_goods_info set goods_name='iphone5s' where id=209";
$db = new Db($sql1);
//$db = new Db($sql2);
//$db = new Db($sql3);
//$db = new Db($sql4);
var_dump($db->get_res());

*/
最后编辑: admin  文档更新时间: 2021-03-16 21:50   作者:admin